From 3ec19f068aac2577e3c3522c4617d78956ec38a7 Mon Sep 17 00:00:00 2001 From: kate Date: Wed, 4 Mar 2020 16:44:11 +0100 Subject: [PATCH 1/8] redirect back fix after new task creation --- .../web/page/admin/resources/ResourceContentPanel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java index 7b5789e06ec..5fc8c40919e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java @@ -421,7 +421,8 @@ private void newTaskPerformed(String category, String archetypeOid, AjaxRequestT } taskType.setOwnerRef(ObjectTypeUtil.createObjectRef(SecurityUtils.getPrincipalUser().getOid(), ObjectTypes.USER)); - setResponsePage(new PageTask(taskType.asPrismObject(), true)); + + getPageBase().navigateToNext(new PageTask(taskType.asPrismObject(), true)); } private ObjectQuery createInTaskOidQuery(List tasksList){ From e66a59641ef956e4800e21a2678a30a550bd9aaf Mon Sep 17 00:00:00 2001 From: kate Date: Wed, 4 Mar 2020 21:12:04 +0100 Subject: [PATCH 2/8] MID-6015 fix: change password to the same value --- .../api/component/password/PasswordPanel.java | 4 ++++ .../password/PasswordPropertyPanel.java | 24 +++++++++++-------- .../prism/ProtectedStringTypeWrapperImpl.java | 2 -- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java index 5df111244b7..f3659f14f7f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java @@ -115,6 +115,8 @@ protected void onComponentTag(ComponentTag tag) { protected void onUpdate(AjaxRequestTarget target) { boolean required = !StringUtils.isEmpty(password1.getModelObject()); password2.setRequired(required); + + changePasswordPerformed(); //fix of MID-2463 // target.add(password2); // target.appendJavaScript("$(\"#"+ password2.getMarkupId() +"\").focus()"); @@ -322,4 +324,6 @@ public void setObject(String object) { } } } + + protected void changePasswordPerformed(){} } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPropertyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPropertyPanel.java index 49f75832006..26337a9e861 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPropertyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPropertyPanel.java @@ -9,6 +9,7 @@ import com.evolveum.midpoint.gui.api.factory.GuiComponentFactory; import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.web.component.prism.ValueStatus; import com.evolveum.midpoint.web.page.admin.users.PageUser; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import org.apache.wicket.Component; @@ -31,17 +32,20 @@ public PasswordPropertyPanel(String id, IModel> item, GuiComponentFactory factory, ItemVisibilityHandler visibilityHandler, ItemEditabilityHandler editabilityHandler) { - PasswordPanel passwordPanel; -// if (!(getPageBase() instanceof PageUser)) { -// passwordPanel = new PasswordPanel(ID_PASSWORD_PANEL, new ItemRealValueModel<>(item.getModel()), -// getModelObject() != null && getModelObject().isReadOnly(), getModelObject() == null); - -// } else { -// - passwordPanel = new PasswordPanel(ID_PASSWORD_PANEL, new ItemRealValueModel<>(item.getModel()), + PasswordPanel passwordPanel = new PasswordPanel(ID_PASSWORD_PANEL, new ItemRealValueModel<>(item.getModel()), getModelObject() != null && getModelObject().isReadOnly(), - item.getModelObject() == null || item.getModelObject().getRealValue() == null ); -// } + item.getModelObject() == null || item.getModelObject().getRealValue() == null ){ + private static final long serialVersionUID = 1L; + + @Override + protected void changePasswordPerformed(){ + PrismPropertyValueWrapper itemModel = item.getModelObject(); + if (itemModel != null){ + itemModel.setStatus(ValueStatus.MODIFIED); + } + } + + }; passwordPanel.setOutputMarkupId(true); item.add(passwordPanel); return passwordPanel; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ProtectedStringTypeWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ProtectedStringTypeWrapperImpl.java index 94510ba82d7..7804bee7328 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ProtectedStringTypeWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ProtectedStringTypeWrapperImpl.java @@ -25,8 +25,6 @@ public class ProtectedStringTypeWrapperImpl extends PrismPropertyWrapperImpl parent, PrismProperty item, ItemStatus status) { super(parent, item, status); - -// getItem().setRealValue(null); } @Override From 71224cc25f427e374852c5078726c95a1bb664cf Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Wed, 4 Mar 2020 21:59:49 +0100 Subject: [PATCH 3/8] added @UnusedTestElement annotation This is to indicate suspicious unused stuff, that we should check and resolve. Didn't want to use TODO as we have tons of those. --- .../tools/testng/UnusedTestElement.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/UnusedTestElement.java diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/UnusedTestElement.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/UnusedTestElement.java new file mode 100644 index 00000000000..770f10563aa --- /dev/null +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/UnusedTestElement.java @@ -0,0 +1,22 @@ +package com.evolveum.midpoint.tools.testng; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates unintentionally unused test, test method or any other test supporting method. + * For test classes it mostly means they are not in suite. + * Use comments, not this annotation to indicate that method/field is prepared for future. + * Marking something with this annotation means a problem that should be eventually resolved. + */ +@Retention(RetentionPolicy.SOURCE) +@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) +public @interface UnusedTestElement { + + /** + * Typically documents the reason. + */ + String value() default ""; +} From 6d41e45c741d2e21b6efaf237758942351b601cf Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Wed, 4 Mar 2020 22:00:43 +0100 Subject: [PATCH 4/8] added OperationResultTestMixin providing createOperationResult methods --- .../test/util/OperationResultTestMixin.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 infra/test-util/src/main/java/com/evolveum/midpoint/test/util/OperationResultTestMixin.java diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/OperationResultTestMixin.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/OperationResultTestMixin.java new file mode 100644 index 00000000000..1039d9374bb --- /dev/null +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/OperationResultTestMixin.java @@ -0,0 +1,25 @@ +package com.evolveum.midpoint.test.util; + +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.tools.testng.MidpointTestMixin; + +/** + * Mixin interface adding methods for {@link OperationResult} creation with context in its name. + * It is based on {@link MidpointTestMixin} and provides all its operations too. + */ +public interface OperationResultTestMixin extends MidpointTestMixin { + + /** + * Creates new {@link OperationResult} with name equal to {@link #contextName()}. + */ + default OperationResult createOperationResult() { + return new OperationResult(contextName()); + } + + /** + * Creates new {@link OperationResult} with name prefixed by {@link #contextName()}. + */ + default OperationResult createOperationResult(String nameSuffix) { + return new OperationResult(contextName() + "." + nameSuffix); + } +} From 2bc7d459addc8988faa7947ea351feb5fdf5bd62 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Wed, 4 Mar 2020 22:03:13 +0100 Subject: [PATCH 5/8] tons of test cleanup, TEST_NAME/title/reformat/logger Also OperationResultTestMixin was added where needed. --- .../TestIntegrationObjectWrapperFactory.java | 111 +-- .../midpoint/gui/TestPageAccount.java | 8 +- .../evolveum/midpoint/gui/TestPageOrg.java | 10 +- .../evolveum/midpoint/gui/TestPageRole.java | 39 +- .../gui/TestPageSystemConfiguration.java | 10 +- .../evolveum/midpoint/gui/TestPageUser.java | 12 +- .../midpoint/gui/TestWrapperDelta.java | 39 +- .../web/AbstractGuiIntegrationTest.java | 27 +- ...AbstractInitializedGuiIntegrationTest.java | 6 +- .../midpoint/web/TestIntegrationSecurity.java | 79 +- .../midpoint/common/LocalizationTest.java | 3 +- .../validator/test/BasicValidatorTest.java | 51 +- .../UnknownNodeSkipSchemaValidationTest.java | 5 +- .../test/UnknownNodeValidationTest.java | 15 +- .../midpoint/prism/util/PrismTestUtil.java | 25 +- .../midpoint/prism/impl/ItemImpl.java | 2 +- .../midpoint/prism/AbstractPrismTest.java | 4 - .../midpoint/schema/AbstractSchemaTest.java | 9 + .../midpoint/schema/TestQueryConverter.java | 114 ++- .../midpoint/schema/TestSchemaDelta.java | 35 - .../AbstractContainerValueParserTest.java | 4 +- .../schema/parser/AbstractParserTest.java | 31 +- .../parser/TestParseApprovalContext.java | 4 - .../parser/TestParseCertificationCase.java | 4 - .../midpoint/schema/parser/TestParseForm.java | 6 - .../schema/parser/TestParseMapping.java | 4 - .../schema/parser/TestParseMappingConst.java | 5 - .../schema/parser/TestParseMappings.java | 4 - .../schema/parser/TestParseMetarole.java | 6 - .../schema/parser/TestParseObjects.java | 1 - .../parser/TestParseObjectsIteratively.java | 1 - .../TestParseObjectsIterativelyFirstTwo.java | 1 - .../TestParseObjectsIterativelyWrong.java | 1 - .../schema/parser/TestParseResource.java | 14 - .../schema/parser/TestParseScriptOutput.java | 7 - .../parser/TestParseScriptingExpression.java | 11 +- .../TestParseScriptingExpressionXsiType.java | 2 - .../schema/parser/TestParseShadow.java | 6 - .../parser/TestParseSystemConfiguration.java | 6 - .../midpoint/schema/parser/TestParseUser.java | 6 - .../parser/TestParseUserPolyString.java | 6 - .../schema/processor/TestResourceSchema.java | 8 +- .../test/util/AbstractSpringTest.java | 2 +- .../midpoint/test/util/MidPointAsserts.java | 130 ++- .../com/evolveum/midpoint/util/DebugUtil.java | 15 - .../model/common/AbstractModelCommonTest.java | 14 +- .../common/expression/TestExpression.java | 42 +- .../expression/TestExpressionProfileSafe.java | 6 +- .../common/expression/TestExpressionUtil.java | 5 +- .../expression/script/AbstractScriptTest.java | 199 ++-- .../script/TestGroovyExpressions.java | 68 +- .../script/TestGroovyExpressionsSandbox.java | 17 +- .../expression/script/TestScriptCaching.java | 75 +- .../script/TestVelocityExpressions.java | 52 +- .../common/mapping/MappingTestEvaluator.java | 280 +++--- .../common/mapping/TestMappingComplex.java | 69 +- .../common/mapping/TestMappingDomain.java | 27 +- .../mapping/TestMappingDynamicSimple.java | 205 ++-- .../mapping/TestMappingDynamicSysVar.java | 36 +- .../common/mapping/TestMappingStatic.java | 24 +- .../impl/expr/ExpressionHandlerImplTest.java | 21 +- .../model/impl/expr/TestModelExpressions.java | 42 +- .../model/impl/lens/TestAssignedMappings.java | 3 - .../model/impl/lens/TestClockwork.java | 6 +- .../model/impl/lens/TestPasswordPolicy.java | 24 +- .../model/impl/lens/TestReconScript.java | 8 +- .../model/impl/migrator/TestMigrator.java | 7 +- .../model/impl/visualizer/TestVisualizer.java | 30 +- ...bstractConfiguredModelIntegrationTest.java | 2 +- ...stractInitializedModelIntegrationTest.java | 10 +- .../midpoint/model/intest/TestAudit.java | 86 +- .../intest/TestConnectorMultiInstance.java | 143 ++- .../model/intest/TestIterativeTasks.java | 37 +- .../intest/TestModelServiceContract.java | 4 +- .../midpoint/model/intest/TestResources.java | 67 +- .../model/intest/TestStrangeCases.java | 121 ++- .../archetypes/AbstractArchetypesTest.java | 2 - .../intest/archetypes/TestCollections.java | 39 +- .../gensync/TestAssociationInbound.java | 11 +- .../model/intest/gensync/TestEditSchema.java | 12 +- .../intest/importer/AbstractImportTest.java | 195 ++-- .../AbstractDirectManualResourceTest.java | 20 +- .../AbstractGroupingManualResourceTest.java | 126 +-- .../manual/AbstractManualResourceTest.java | 425 ++++---- .../model/intest/manual/CsvBackingStore.java | 44 +- .../manual/CsvDisablingBackingStore.java | 7 - ...DummyItsmIntegrationConnectorInstance.java | 2 +- .../manual/TestDummyItsmIntegration.java | 27 +- .../model/intest/manual/TestSemiManual.java | 58 +- .../TestSemiManualDisableSlowProposed.java | 22 +- .../TestSemiManualGroupingProposed.java | 18 +- .../manual/TestSemiManualSlowProposed.java | 10 +- .../multi/TestMultiConnectorResources.java | 38 +- .../model/intest/multi/TestMultiResource.java | 4 +- .../intest/negative/TestBrokenResources.java | 2 +- .../password/TestPasswordDefaultHashing.java | 4 +- .../intest/scripting/TestScriptingBasic.java | 166 +--- .../intest/security/TestSecurityBasic.java | 136 +-- .../sync/TestLiveSyncTaskMechanics.java | 20 - .../TestValidityRecomputeTaskPartitioned.java | 2 +- .../test/AbstractModelIntegrationTest.java | 55 +- ...gnmentCandidatesSpecificationAsserter.java | 4 +- .../asserter/CompiledGuiProfileAsserter.java | 4 +- .../test/asserter/ElementContextAsserter.java | 4 +- .../test/asserter/FocusContextAsserter.java | 4 +- .../test/asserter/ModelContextAsserter.java | 4 +- .../asserter/ProjectionContextAsserter.java | 4 +- .../RoleSelectionSpecificationAsserter.java | 4 +- ...electionSpecificationRelationAsserter.java | 4 +- .../impl/TestTransportUtils.java | 48 +- .../evolveum/midpoint/report/TestReport.java | 2 +- .../impl/association/TestAddAssociation.java | 10 +- .../wf/impl/other/ManualResourceTest.java | 126 ++- .../AbstractProvisioningIntegrationTest.java | 9 +- .../impl/TestConnectorDiscovery.java | 4 +- .../provisioning/impl/TestDBTable.java | 82 +- .../impl/async/TestAsyncUpdate.java | 7 +- .../impl/csv/AbstractCsvTest.java | 4 +- .../provisioning/impl/csv/TestCsvGuid.java | 6 +- .../impl/csv/TestCsvUsername.java | 6 +- .../impl/dummy/AbstractBasicDummyTest.java | 24 +- .../impl/dummy/AbstractDummyTest.java | 99 +- .../provisioning/impl/dummy/TestDummy.java | 10 +- .../impl/dummy/TestDummyHacks.java | 12 +- .../impl/dummy/TestDummyNegative.java | 2 +- .../impl/dummy/TestDummyParallelism.java | 4 +- ...yPrioritiesAndReadReplaceLegacyUpdate.java | 4 - .../TestDummyResourceAndSchemaCaching.java | 4 - .../impl/dummy/TestDummySchemaless.java | 6 +- .../impl/dummy/TestDummySecurity.java | 4 +- .../manual/AbstractManualResourceTest.java | 6 +- .../impl/manual/TestSemiManual.java | 23 +- ...ObjectShadowChangeDescriptionAsserter.java | 4 +- .../impl/mock/SynchronizationServiceMock.java | 3 +- .../impl/opendj/AbstractOpenDjTest.java | 16 +- .../provisioning/impl/opendj/TestOpenDj.java | 601 ++++-------- .../opendj/TestOpenDjIncompletePassword.java | 12 +- .../impl/opendj/TestOpenDjNegative.java | 337 +++---- .../impl/opendj/TestSynchronization.java | 6 +- .../ucf/impl/connid/AbstractUcfDummyTest.java | 9 + .../ucf/impl/connid/TestUcfDummy.java | 2 - .../ucf/impl/connid/TestUcfDummyMulti.java | 63 +- .../ucf/impl/connid/TestUcfOpenDj.java | 46 +- .../repo/cache/TestRepositoryCache.java | 12 +- .../common/commandline/TestCommandLine.java | 4 +- repo/repo-sql-impl-test/pom.xml | 12 +- .../midpoint/repo/sql/AbstractPhotoTest.java | 11 +- .../midpoint/repo/sql/AddGetObjectTest.java | 67 +- .../midpoint/repo/sql/AddOverwriteTest.java | 7 - .../repo/sql/AuditCleanupPerformanceTest.java | 21 +- .../evolveum/midpoint/repo/sql/AuditTest.java | 40 +- .../midpoint/repo/sql/BaseSQLRepoTest.java | 63 +- .../midpoint/repo/sql/CertificationTest.java | 16 +- .../midpoint/repo/sql/CleanupTest.java | 22 +- .../midpoint/repo/sql/ConcurrencyTest.java | 128 ++- .../midpoint/repo/sql/DataSourceTest.java | 1 + .../midpoint/repo/sql/DeleteTest.java | 18 +- .../midpoint/repo/sql/DeleteTestSimple.java | 27 +- .../repo/sql/EmbeddedServerModeTest.java | 11 +- .../midpoint/repo/sql/EncodingTest.java | 61 +- .../sql/ExtDictionaryConcurrencyTest.java | 75 +- .../midpoint/repo/sql/ExtDictionaryTest.java | 45 +- .../midpoint/repo/sql/ExtensionTest.java | 41 +- .../repo/sql/ListAccountShadowOwnerTest.java | 26 +- .../midpoint/repo/sql/LookupTableTest.java | 100 +- .../repo/sql/ModifyAssignmentTest.java | 16 +- .../midpoint/repo/sql/ModifyTest.java | 164 ++-- .../midpoint/repo/sql/ModifyTestReindex.java | 14 +- .../midpoint/repo/sql/ModifyUser.java | 15 +- .../repo/sql/ObjectDeltaUpdaterTest.java | 10 +- .../midpoint/repo/sql/OrgStructTest.java | 99 +- .../midpoint/repo/sql/PerformanceTest.java | 24 +- .../repo/sql/QueryInterpreter2Test.java | 349 +++---- .../repo/sql/RAnyConverterStaticTest.java | 35 +- .../evolveum/midpoint/repo/sql/RUtilTest.java | 25 +- .../midpoint/repo/sql/ResourceModifyTest.java | 11 +- .../repo/sql/SearchIterativeTest.java | 56 +- .../repo/sql/SearchShadowOwnerTest.java | 6 +- .../midpoint/repo/sql/SearchTest.java | 122 ++- .../midpoint/repo/sql/SequenceTest.java | 24 +- .../sql/closure/AbstractOrgClosureTest.java | 206 ++-- .../closure/OrgClosureConcurrencyTest.java | 119 ++- .../closure/OrgClosureOverwriteAddTest.java | 6 +- .../midpoint/test/AbstractHigherUnitTest.java | 10 +- .../test/AbstractIntegrationTest.java | 49 +- .../midpoint/test/IntegrationTestTools.java | 18 +- .../test/asserter/DummyObjectAsserter.java | 4 +- .../asserter/ObjectReferenceAsserter.java | 4 +- .../prism/ComplexTypeDefinitionAsserter.java | 4 +- .../prism/DeltaSetTripleAsserter.java | 4 +- .../asserter/prism/ObjectDeltaAsserter.java | 4 +- .../asserter/prism/ObjectFilterAsserter.java | 5 +- .../asserter/prism/PolyStringAsserter.java | 4 +- .../PrismContainerDefinitionAsserter.java | 4 +- .../prism/PrismDefinitionAsserter.java | 4 +- .../PrismPropertyDefinitionAsserter.java | 4 +- .../asserter/prism/PrismSchemaAsserter.java | 4 +- ...ectClassComplexTypeDefinitionAsserter.java | 4 +- .../RefinedResourceSchemaAsserter.java | 4 +- .../ResourceAttributeDefinitionAsserter.java | 4 +- .../impl/MidPointPrincipalManagerMock.java | 11 +- .../midpoint/security/impl/TestEmpty.java | 20 +- .../quartzimpl/AbstractTaskManagerTest.java | 10 +- .../midpoint/task/quartzimpl/CleanupTest.java | 5 +- .../task/quartzimpl/TestMiscellaneous.java | 1 - .../task/quartzimpl/TestPartitioning.java | 70 +- .../TestQuartzTaskManagerContract.java | 77 +- .../quartzimpl/TestWorkBucketStrategies.java | 39 +- .../task/quartzimpl/TestWorkDistribution.java | 50 +- .../testing/conntest/AbstractLdapTest.java | 23 +- .../testing/conntest/TestOpenLdap.java | 4 +- .../AbstractAdLdapMultidomainRunAsTest.java | 26 +- .../ad/AbstractAdLdapMultidomainTest.java | 136 +-- .../conntest/ad/AbstractAdLdapRawTest.java | 2 +- .../conntest/ad/AbstractAdLdapTest.java | 40 +- .../ad/{AdUtils.java => AdTestMixin.java} | 86 +- .../longtest/TestGenericSynchronization.java | 6 +- .../midpoint/testing/longtest/TestLdap.java | 29 +- .../testing/longtest/TestLdapComplex.java | 29 +- .../testing/longtest/TestLdapUniversity.java | 2 +- .../testing/longtest/TestOrgHierarchy.java | 65 +- .../midpoint/testing/longtest/TestRunAs.java | 59 +- .../testing/rest/RestServiceInitializer.java | 11 +- .../TestRestServiceProxyAuthentication.java | 12 +- ...TestSecurityQuestionChallengeResponse.java | 51 +- .../samples/test/AbstractSampleTest.java | 32 +- .../midpoint/testing/sanity/TestSanity.java | 678 ++++++------- .../story/TestConsistencyMechanism.java | 920 ++++++++---------- .../testing/story/TestManyThreads.java | 25 +- .../story/TestPlentyOfAssignments.java | 89 +- .../testing/story/TestThresholds.java | 4 +- .../story/TestThresholdsReconFull.java | 4 +- .../midpoint/testing/story/TestVillage.java | 2 +- .../story/notorious/TestNotoriousOrg.java | 6 +- .../story/notorious/TestNotoriousRole.java | 72 +- .../tools/testng/AbstractUnitTest.java | 2 +- .../tools/testng/MidpointTestMixin.java | 21 +- 237 files changed, 4270 insertions(+), 6389 deletions(-) rename testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/{AdUtils.java => AdTestMixin.java} (75%) diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java index 06178e18898..7b5479c0778 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java @@ -6,6 +6,22 @@ */ package com.evolveum.midpoint.gui; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.web.AdminGuiTestConstants.*; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ActiveProfiles; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.DummyGroup; import com.evolveum.midpoint.gui.api.prism.*; import com.evolveum.midpoint.gui.api.util.ModelServiceLocator; @@ -27,7 +43,6 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.AdminGuiTestConstants; @@ -35,20 +50,6 @@ import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.prism.ValueStatus; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ActiveProfiles; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; - -import static com.evolveum.midpoint.web.AdminGuiTestConstants.*; -import static org.testng.AssertJUnit.*; /** * @author semancik @@ -128,9 +129,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100CreateWrapperUserJack() throws Exception { - final String TEST_NAME = "test100CreateWrapperUserJack"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -147,7 +146,7 @@ public void test100CreateWrapperUserJack() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, userOld, ItemStatus.NOT_CHANGED); assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); @@ -214,13 +213,10 @@ private void assertContainersPaths(PrismObjectWrapper objectWrapper, Collecti */ @Test public void test110CreateWrapperUserNewEmpty() throws Exception { - final String TEST_NAME = "test110CreateWrapperUserNew"; PrismObject user = getUserDefinition().instantiate(); - // WHEN when(); - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObjectWrapperFactory factory = getServiceLocator(task).findObjectWrapperFactory(user.getDefinition()); @@ -230,10 +226,8 @@ public void test110CreateWrapperUserNewEmpty() throws Exception { PrismObjectWrapper objectWrapper = factory.createObjectWrapper(user, ItemStatus.ADDED, context); - // THEN then(); - - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, getUserDefinition().instantiate(), ItemStatus.ADDED); assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); @@ -284,20 +278,17 @@ public void test110CreateWrapperUserNewEmpty() throws Exception { */ @Test public void test112CreateWrapperUserNewman() throws Exception { - final String TEST_NAME = "test112CreateWrapperUserNewman"; PrismObject user = getUserDefinition().instantiate(); - // WHEN when(); - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ModelServiceLocator modelServiceLocator = getServiceLocator(task); PrismObjectWrapperFactory factory = modelServiceLocator.findObjectWrapperFactory(user.getDefinition()); WrapperContext context = new WrapperContext(task, result); - PrismObjectWrapper objectWrapper = factory.createObjectWrapper(user, - ItemStatus.ADDED, context); + PrismObjectWrapper objectWrapper = + factory.createObjectWrapper(user, ItemStatus.ADDED, context); PrismObjectValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); @@ -310,15 +301,15 @@ public void test112CreateWrapperUserNewman() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, getUserDefinition().instantiate(), ItemStatus.ADDED); assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); - WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), (ItemPath)null, user, ItemStatus.ADDED); + WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), null, user, ItemStatus.ADDED); assertEquals("wrong number of containers in "+objectWrapper, 1, objectWrapper.getValues().size()); WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_NEWMAN_USERNAME)); - WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE, null); + WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE); WrapperTestUtil.assertPropertyWrapper(mainContainerValueWrapper, extensionPath(PIRACY_SHIP), USER_NEWMAN_SHIP); PrismContainerWrapper activationContainerWrapper = objectWrapper.findContainer(UserType.F_ACTIVATION); @@ -361,14 +352,13 @@ public void test112CreateWrapperUserNewman() throws Exception { @Test public void test102CreateWrapperUserEmpty() throws Exception { - final String TEST_NAME = "test102CreateWrapperUserEmpty"; PrismObject user = getUser(USER_EMPTY_OID); PrismObject userOld = user.clone(); // WHEN when(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ModelServiceLocator modelServiceLocator = getServiceLocator(task); @@ -380,16 +370,16 @@ public void test102CreateWrapperUserEmpty() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, userOld, ItemStatus.NOT_CHANGED); assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); - WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), (ItemPath)null, user, ItemStatus.NOT_CHANGED); + WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), null, user, ItemStatus.NOT_CHANGED); assertEquals("wrong number of containers in "+objectWrapper, 1, objectWrapper.getValues().size()); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_EMPTY_USERNAME)); - WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE, null); + WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE); // Not sure about this // ContainerWrapper activationContainerWrapper = objectWrapper.findContainer(ItemPath.create(UserType.F_ACTIVATION)); @@ -421,7 +411,6 @@ public void test102CreateWrapperUserEmpty() throws Exception { @Test public void test150CreateWrapperShadow() throws Exception { - final String TEST_NAME = "test150CreateWrapperShadow"; PrismObject shadow = getShadowModel(accountJackOid); shadow.findReference(ShadowType.F_RESOURCE_REF).getValue().setObject(resourceDummy); display("Shadow", shadow); @@ -429,7 +418,7 @@ public void test150CreateWrapperShadow() throws Exception { // WHEN when(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ModelServiceLocator modelServiceLocator = getServiceLocator(task); @@ -439,10 +428,7 @@ public void test150CreateWrapperShadow() throws Exception { PrismObjectWrapper objectWrapper = factory.createObjectWrapper(shadow, ItemStatus.NOT_CHANGED, context); assertTrue("Wrong wrapper created. Expected ShadowWrapper but got " + objectWrapper.getClass().getSimpleName(), objectWrapper instanceof ShadowWrapper); - ShadowWrapper shadowWrapper = (ShadowWrapper) objectWrapper; - - // THEN then(); display("Wrapper after", objectWrapper); @@ -515,7 +501,7 @@ public void test160CreateWrapperOrgScummBar() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "org description", org, orgOld, ItemStatus.NOT_CHANGED); assertContainersPaths(objectWrapper, BASIC_ORG_CONTAINERS_PATHS); @@ -563,8 +549,6 @@ public void test160CreateWrapperOrgScummBar() throws Exception { @Test public void test220AssignRoleLandluberToWally() throws Exception { - final String TEST_NAME = "test220AssignRoleLandluberToWally"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -651,13 +635,13 @@ public void test240OrgScummBarModifyTransformDescription() throws Exception { Task task = getTestTask(); PrismObjectWrapper objectWrapper = createObjectWrapper(task, org, ItemStatus.NOT_CHANGED); - IntegrationTestTools.display("Wrapper before", objectWrapper); + PrismTestUtil.display("Wrapper before", objectWrapper); PrismObjectValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); modifyPropertyWrapper(getServiceLocator(task), mainContainerValueWrapper, extensionPath(PIRACY_TRANSFORM_DESCRIPTION), "Whatever"); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); // WHEN when(); @@ -682,13 +666,12 @@ public void test240OrgScummBarModifyTransformDescription() throws Exception { @Test public void test241OrgScummBarModifyTransformProperties() throws Exception { - final String TEST_NAME = "test241OrgScummBarModifyTransformProperties"; PrismObject org = getObject(OrgType.class, ORG_SCUMM_BAR_OID); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); PrismObjectWrapper objectWrapper = createObjectWrapper(task, org, ItemStatus.NOT_CHANGED); - IntegrationTestTools.display("Wrapper before", objectWrapper); + PrismTestUtil.display("Wrapper before", objectWrapper); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); PrismContainerWrapper transformContainerWrapper = mainContainerValueWrapper.findContainer(extensionPath(PIRACY_TRANSFORM)); @@ -700,7 +683,7 @@ public void test241OrgScummBarModifyTransformProperties() throws Exception { display("A value wrapper", valueWrapperA); modifyTransformProp(valueWrapperA, PIRACY_REPLACEMENT, "Ahoy"); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); // WHEN when(); @@ -725,12 +708,11 @@ public void test241OrgScummBarModifyTransformProperties() throws Exception { @Test public void test242OrgScummBarAddTransform() throws Exception { - final String TEST_NAME = "test242OrgScummBarAddTransform"; PrismObject org = getObject(OrgType.class, ORG_SCUMM_BAR_OID); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); PrismObjectWrapper objectWrapper = createObjectWrapper(task, org, ItemStatus.NOT_CHANGED); - IntegrationTestTools.display("Wrapper before", objectWrapper); + PrismTestUtil.display("Wrapper before", objectWrapper); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); PrismContainerWrapper transformContainerWrapper = mainContainerValueWrapper.findContainer(extensionPath(PIRACY_TRANSFORM)); @@ -747,7 +729,7 @@ public void test242OrgScummBarAddTransform() throws Exception { modifyTransformProp(newContainerValueWrapper, PIRACY_PATTERN, "D"); modifyTransformProp(newContainerValueWrapper, PIRACY_REPLACEMENT, "Doubloon"); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); // WHEN when(); @@ -787,19 +769,18 @@ public void test242OrgScummBarAddTransform() throws Exception { */ @Test public void test250OrgMinistryOrRumModifyTransformDescription() throws Exception { - final String TEST_NAME = "test250OrgMinistryOrRumModifyTransformDescription"; PrismObject org = getObject(OrgType.class, ORG_MINISTRY_OF_RUM_OID); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); PrismObjectWrapper objectWrapper = createObjectWrapper(task, org, ItemStatus.NOT_CHANGED); - IntegrationTestTools.display("Wrapper before", objectWrapper); + PrismTestUtil.display("Wrapper before", objectWrapper); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); modifyPropertyWrapper(getServiceLocator(task), mainContainerValueWrapper, extensionPath(PIRACY_TRANSFORM_DESCRIPTION), "Whatever"); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); // WHEN when(); @@ -870,7 +851,6 @@ private void modifyTransformProp(PrismContainerValueWrapper trans */ @Test public void test800EditSchemaJackPropReadAllModifySomeUser() throws Exception { - final String TEST_NAME = "test800EditSchemaJackPropReadAllModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_USER_OID); @@ -887,7 +867,7 @@ public void test800EditSchemaJackPropReadAllModifySomeUser() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); assertEquals("Wrong object wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadOnly()); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); @@ -941,7 +921,6 @@ public void test800EditSchemaJackPropReadAllModifySomeUser() throws Exception { */ @Test public void test802EditSchemaJackPropReadSomeModifySomeUser() throws Exception { - final String TEST_NAME = "test800EditSchemaJackPropReadAllModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID); @@ -959,7 +938,7 @@ public void test802EditSchemaJackPropReadSomeModifySomeUser() throws Exception { // THEN then(); - IntegrationTestTools.display("Wrapper after", objectWrapper); + PrismTestUtil.display("Wrapper after", objectWrapper); assertEquals("Wrong object wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadOnly()); PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageAccount.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageAccount.java index 7d525d62a6e..1d3ee08db07 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageAccount.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageAccount.java @@ -18,8 +18,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.component.AjaxSubmitButton; import com.evolveum.midpoint.web.page.admin.resources.content.PageAccount; @@ -35,8 +33,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestPageAccount extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPageAccount.class); - private static final String FORM_SAVE = "mainForm:save"; @Override @@ -44,7 +40,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); PrismObject systemConfig = parseObject(SYSTEM_CONFIGURATION_FILE); - LOGGER.info("adding system config page"); + logger.info("adding system config page"); addObject(systemConfig, ModelExecuteOptions.createOverwrite(), initTask, initResult); } @@ -73,7 +69,7 @@ private PageAccount renderPage(String userOid) { } private PageAccount renderPageWithParams(PageParameters params) { - LOGGER.info("render page account"); + logger.info("render page account"); if(params == null) { params = new PageParameters(); } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageOrg.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageOrg.java index 127a80f33d9..6636ee7ac11 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageOrg.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageOrg.java @@ -22,8 +22,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.page.admin.users.PageOrgTree; import com.evolveum.midpoint.web.page.admin.users.PageOrgUnit; @@ -38,8 +36,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestPageOrg extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPageOrg.class); - private static final String MAIN_FORM = "mainPanel:mainForm"; // private static final String FORM_INPUT_DESCRIPTION = "tabPanel:panel:basicSystemConfiguration:values:0:value:propertiesLabel:properties:1:property:values:0:valueContainer:form:input:input"; private static final String PATH_FORM_NAME = "tabPanel:panel:main:values:0:value:propertiesLabel:properties:0:property:values:0:valueContainer:form:input:originValueContainer:origValueWithButton:origValue:input"; @@ -53,7 +49,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); PrismObject systemConfig = parseObject(SYSTEM_CONFIGURATION_FILE); - LOGGER.info("adding system config page"); + logger.info("adding system config page"); addObject(systemConfig, ModelExecuteOptions.createOverwrite(), initTask, initResult); } @@ -79,7 +75,7 @@ public void test003testAddNewOrg() throws Exception { PrismObject newOrg = findObjectByName(OrgType.class, NEW_ORG_NAME); assertNotNull(newOrg, "New org not created."); - LOGGER.info("created org: {}", newOrg.debugDump()); + logger.info("created org: {}", newOrg.debugDump()); } @Test @@ -101,7 +97,7 @@ public void test004testCreateChild() throws Exception { } private void renderPage(Class expectedRenderedPageClass) { - LOGGER.info("render page system configuration"); + logger.info("render page system configuration"); PageParameters params = new PageParameters(); tester.startPage(expectedRenderedPageClass, params); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageRole.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageRole.java index a699bc67655..034b4094126 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageRole.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageRole.java @@ -6,32 +6,31 @@ */ package com.evolveum.midpoint.gui; +import static org.testng.Assert.assertNotNull; + +import static com.evolveum.midpoint.web.AdminGuiTestConstants.USER_JACK_OID; +import static com.evolveum.midpoint.web.AdminGuiTestConstants.USER_JACK_USERNAME; + +import org.apache.wicket.Page; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.tester.FormTester; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ActiveProfiles; +import org.testng.annotations.Test; + import com.evolveum.midpoint.gui.test.TestMidPointSpringApplication; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; import com.evolveum.midpoint.web.page.admin.roles.PageRole; -import com.evolveum.midpoint.web.page.admin.users.PageOrgUnit; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import org.apache.wicket.Page; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.tester.FormTester; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ActiveProfiles; -import org.testng.annotations.Test; - -import static com.evolveum.midpoint.web.AdminGuiTestConstants.USER_JACK_OID; -import static com.evolveum.midpoint.web.AdminGuiTestConstants.USER_JACK_USERNAME; -import static org.testng.Assert.assertNotNull; /** * @author Hiroyuki Wada @@ -41,8 +40,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestPageRole extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPageOrg.class); - private static final String MAIN_FORM = "mainPanel:mainForm"; private static final String PATH_FORM_NAME = "tabPanel:panel:main:values:0:value:propertiesLabel:properties:0:property:values:0:valueContainer:form:input:originValueContainer:origValueWithButton:origValue:input"; private static final String FORM_SAVE = "save"; @@ -52,7 +49,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); PrismObject systemConfig = parseObject(SYSTEM_CONFIGURATION_FILE); - LOGGER.info("adding system config page"); + logger.info("adding system config page"); addObject(systemConfig, ModelExecuteOptions.createOverwrite(), initTask, initResult); } @@ -67,13 +64,13 @@ public void test002testAddNewRole() throws Exception { FormTester formTester = tester.newFormTester(MAIN_FORM, false); formTester.setValue(PATH_FORM_NAME, "newRole"); - formTester = formTester.submit(FORM_SAVE); + formTester.submit(FORM_SAVE); Thread.sleep(5000); PrismObject newRole = findObjectByName(RoleType.class, "newRole"); assertNotNull(newRole, "New role not created."); - LOGGER.info("created role: {}", newRole.debugDump()); + logger.info("created role: {}", newRole.debugDump()); } /** @@ -134,7 +131,7 @@ private Page renderPage(Class expectedRenderedPageClass) { } private Page renderPage(Class expectedRenderedPageClass, String oid) { - LOGGER.info("render page role"); + logger.info("render page role"); PageParameters params = new PageParameters(); if (oid != null) { params.add(OnePageParameterEncoder.PARAMETER, oid); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageSystemConfiguration.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageSystemConfiguration.java index 4e54844c7da..ab9a1a7bb72 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageSystemConfiguration.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageSystemConfiguration.java @@ -21,8 +21,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; import com.evolveum.midpoint.web.page.admin.home.PageDashboardInfo; @@ -36,8 +34,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestPageSystemConfiguration extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPageSystemConfiguration.class); - private static final String MAIN_FORM = "mainPanel:mainForm"; private static final String FORM_INPUT_DESCRIPTION = "tabPanel:panel:basicSystemConfiguration:values:0:value:propertiesLabel:properties:1:property:values:0:valueContainer:form:input:input"; private static final String FORM_SAVE = "save"; @@ -47,7 +43,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); PrismObject systemConfig = parseObject(SYSTEM_CONFIGURATION_FILE); - LOGGER.info("adding system config page"); + logger.info("adding system config page"); addObject(systemConfig, ModelExecuteOptions.createOverwrite(), initTask, initResult); } @@ -66,7 +62,7 @@ public void test001testModifySystemConfig() throws Exception { String des = "new description"; formTester.setValue(FORM_INPUT_DESCRIPTION, des); - formTester = formTester.submit(FORM_SAVE); + formTester.submit(FORM_SAVE); Thread.sleep(5000); @@ -77,7 +73,7 @@ public void test001testModifySystemConfig() throws Exception { } private PageSystemConfiguration renderPage() { - LOGGER.info("render page system configuration"); + logger.info("render page system configuration"); PageParameters params = new PageParameters(); PageSystemConfiguration pageAccount = tester.startPage(PageSystemConfiguration.class, params); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageUser.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageUser.java index 1771a8975ba..d7162df27af 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageUser.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestPageUser.java @@ -28,8 +28,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.component.objectdetails.AssignmentHolderTypeDetailsTabPanel; import com.evolveum.midpoint.web.component.objectdetails.ObjectHistoryTabPanel; @@ -47,8 +45,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestPageUser extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPageUser.class); - private static final String TAB_MAIN = "mainPanel:mainForm:tabPanel:panel:main"; private static final String TAB_ACTIVATION = "mainPanel:mainForm:tabPanel:panel:activation"; private static final String TAB_PASSWORD = "mainPanel:mainForm:tabPanel:panel:password"; @@ -72,7 +68,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); PrismObject systemConfig = parseObject(SYSTEM_CONFIGURATION_FILE); - LOGGER.info("adding system config page"); + logger.info("adding system config page"); addObject(systemConfig, ModelExecuteOptions.createOverwrite(), initTask, initResult); } @@ -113,7 +109,7 @@ public void test002testAddDelta() throws Exception { PrismObject newUser = findObjectByName(UserType.class, "newUser"); assertNotNull(newUser, "New user not created."); - LOGGER.info("created user: {}", newUser.debugDump()); + logger.info("created user: {}", newUser.debugDump()); } @@ -132,7 +128,7 @@ public void test010renderAssignmentsTab() { } @Test - public void test011renderProjectionsTab() throws Exception { + public void test011renderProjectionsTab() { renderPage(USER_JACK_OID); clickOnTab(1); @@ -207,7 +203,7 @@ private PageUser renderPage(String userOid) { } private PageUser renderPageWithParams(PageParameters params) { - LOGGER.info("render page user"); + logger.info("render page user"); if (params == null) { params = new PageParameters(); } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestWrapperDelta.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestWrapperDelta.java index 3a5ca945126..fb2ac3fca67 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestWrapperDelta.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestWrapperDelta.java @@ -33,9 +33,6 @@ import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.asserter.UserAsserter; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractInitializedGuiIntegrationTest; import com.evolveum.midpoint.web.component.prism.ValueStatus; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -62,8 +59,6 @@ @SpringBootTest(classes = TestMidPointSpringApplication.class) public class TestWrapperDelta extends AbstractInitializedGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestWrapperDelta.class); - private static final String TEST_DIR = "src/test/resources/delta"; private static final File USER_ELAINE = new File(TEST_DIR, "user-elaine.xml"); @@ -78,8 +73,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100modifyUserFullname() throws Exception { - final String TEST_NAME = "test100CreateWrapperUserJack"; - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); @@ -108,9 +102,7 @@ public void test100modifyUserFullname() throws Exception { @Test public void test101modifyUserWeapon() throws Exception { - final String TEST_NAME = "test101modifyUserWeapon"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userElaineBefore = getUser(USER_ELAINE_OID); @@ -136,16 +128,14 @@ public void test101modifyUserWeapon() throws Exception { executeChanges(elaineDelta, null, task, result); PrismObject userElaineAfter = getUser(USER_ELAINE_OID); - LOGGER.info("ELAINE AFTER: {}", userElaineAfter.debugDump()); + logger.info("ELAINE AFTER: {}", userElaineAfter.debugDump()); UserAsserter.forUser(userElaineAfter).extension().assertPropertyValuesEqual(PIRACY_WEAPON, "revolver"); } @Test public void test110modifyUserAddAssignment() throws Exception { - final String TEST_NAME = "test110modifyUserAddAssignment"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userElaineBefore = getUser(USER_ELAINE_OID); @@ -177,9 +167,7 @@ public void test110modifyUserAddAssignment() throws Exception { @Test public void test111modifyUserAssignemnt() throws Exception { - final String TEST_NAME = "test110modifyUserAddAssignment"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userElaineBefore = getUser(USER_ELAINE_OID); @@ -218,7 +206,7 @@ public void test111modifyUserAssignemnt() throws Exception { ObjectDelta delta = objectWrapper.getObjectDelta(); assertModificationsSize(delta, 1); - LOGGER.info("Attr delta: {}", delta.debugDump()); + logger.info("Attr delta: {}", delta.debugDump()); ResourceAttributeDefinitionType expectedvalue = new ResourceAttributeDefinitionType(locator.getPrismContext()); expectedvalue.setRef(new ItemPathType(ItemPath.create(SchemaConstants.ICFS_NAME))); @@ -260,9 +248,8 @@ public void test111modifyUserAssignemnt() throws Exception { @Test public void test200createUser() throws Exception { - String TEST_NAME = "test200createUser"; - - Task task = createSimpleTask(TEST_NAME); +// Task task = getTestTask(); // TODO we don't want customized task here? + Task task = createPlainTask(); OperationResult result = task.getResult(); PrismObjectDefinition def = getServiceLocator(task).getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); @@ -315,9 +302,7 @@ public void test200createUser() throws Exception { @Test public void test300SaveSystemConfigWithoutChanges() throws Exception { - final String TEST_NAME = "test300SaveSystemConfigWithoutChanges"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); SystemConfigurationType systemConfig = getSystemConfiguration(); @@ -332,9 +317,7 @@ public void test300SaveSystemConfigWithoutChanges() throws Exception { @Test public void test301ModifyProfilingClassLoggerOfSystemConfig() throws Exception { - final String TEST_NAME = "test301ModifyProfilingClassLoggerOfSystemConfig"; - Task task = taskManager.createTaskInstance(TEST_NAME); - + Task task = getTestTask(); OperationResult result = task.getResult(); SystemConfigurationType systemConfigBefore = getSystemConfiguration(); @@ -414,7 +397,7 @@ private ExpressionType createAsIsExpression() { private void assertModificationsSize(ObjectDelta delta, int expectedModifications) { assertNotNull("Unexpeted null delta", delta); - LOGGER.trace("Delta: {}", delta.debugDump()); + logger.trace("Delta: {}", delta.debugDump()); Collection> modifications = delta.getModifications(); assertEquals("Unexpected modifications size", expectedModifications, modifications.size()); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java index f11cea93bab..93d13a70749 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java @@ -73,8 +73,6 @@ */ public abstract class AbstractGuiIntegrationTest extends AbstractModelIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(AbstractGuiIntegrationTest.class); - public static final File FOLDER_BASIC = new File("./src/test/resources/basic"); public static final String NS_PIRACY = "http://midpoint.evolveum.com/xml/ns/samples/piracy"; @@ -131,13 +129,13 @@ public abstract class AbstractGuiIntegrationTest extends AbstractModelIntegratio @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.info("before super init"); + logger.info("before super init"); super.initSystem(initTask, initResult); - LOGGER.info("after super init"); + logger.info("after super init"); login(USER_ADMINISTRATOR_USERNAME); - LOGGER.info("user logged in"); + logger.info("user logged in"); tester = new WicketTester(application, true); } @@ -153,28 +151,28 @@ public void afterMethodApplication() { @BeforeClass public void beforeClass() { System.out.println("\n>>>>>>>>>>>>>>>>>>>>>>>> START " + getClass().getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info("\n>>>>>>>>>>>>>>>>>>>>>>>> START {} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName() }); - LOGGER.info("Loalization serivce : {}", localizationService); + logger.info("\n>>>>>>>>>>>>>>>>>>>>>>>> START {} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName() }); + logger.info("Loalization serivce : {}", localizationService); String s = localizationService.translate("midpoint.system.build", null, localizationService.getDefaultLocale()); - LOGGER.info("SsSSSSSSSSSSSSS {}", s); + logger.info("SsSSSSSSSSSSSSS {}", s); } @AfterClass public void afterClass() { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> FINISH " + getClass().getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> FINISH {} <<<<<<<<<<<<<<<<<<<<<<<<\n", new Object[] { getClass().getName() }); + logger.info(">>>>>>>>>>>>>>>>>>>>>>>> FINISH {} <<<<<<<<<<<<<<<<<<<<<<<<\n", new Object[] { getClass().getName() }); } @BeforeMethod public void beforeMethod(Method method) { System.out.println("\n>>>>>>>>>>>>>>>>>>>>>>>> START TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info("\n>>>>>>>>>>>>>>>>>>>>>>>> START {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName(), method.getName() }); + logger.info("\n>>>>>>>>>>>>>>>>>>>>>>>> START {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName(), method.getName() }); } @AfterMethod public void afterMethod(Method method) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> END TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> END {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName(), method.getName() }); + logger.info(">>>>>>>>>>>>>>>>>>>>>>>> END {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName(), method.getName() }); } protected ModelServiceLocator getServiceLocator(final Task pageTask) { @@ -310,15 +308,8 @@ protected ItemPath extensionPath(QName qname) { return ItemPath.create(ObjectType.F_EXTENSION, qname); } - protected Task createSimpleTask(String operation) { - Task task = taskManager.createTaskInstance(operation); - task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); - return task; - } - /** * Emulate closing ModalWindow component. - * @param path */ protected void executeModalWindowCloseCallback(String path) { Component component = tester.getComponentFromLastRenderedPage(path); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java index 02901d3f5d8..6e60db86393 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java @@ -18,8 +18,6 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -29,8 +27,6 @@ */ public abstract class AbstractInitializedGuiIntegrationTest extends AbstractGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(AbstractInitializedGuiIntegrationTest.class); - protected DummyResource dummyResource; protected DummyResourceContoller dummyResourceCtl; protected ResourceType resourceDummyType; @@ -41,7 +37,7 @@ public abstract class AbstractInitializedGuiIntegrationTest extends AbstractGuiI @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); modelService.postInit(initResult); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationSecurity.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationSecurity.java index 98999722901..fc11048e44e 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationSecurity.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationSecurity.java @@ -10,13 +10,8 @@ import static com.evolveum.midpoint.web.AdminGuiTestConstants.USER_JACK_USERNAME; import java.io.File; -import java.io.IOException; -import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.test.TestResource; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; @@ -33,23 +28,16 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.test.TestResource; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.web.security.MidPointGuiAuthorizationEvaluator; +import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik */ -@ContextConfiguration(locations = {"classpath:ctx-admin-gui-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-admin-gui-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIntegrationSecurity extends AbstractInitializedGuiIntegrationTest { @@ -67,8 +55,6 @@ public class TestIntegrationSecurity extends AbstractInitializedGuiIntegrationTe private static final TestResource ROLE_AUTHORIZATION_1 = new TestResource(TEST_DIR, "role-authorization-1.xml", "97984277-e809-4a86-ae9b-d5c40e09df0b"); private static final TestResource ROLE_AUTHORIZATION_2 = new TestResource(TEST_DIR, "role-authorization-2.xml", "96b02d58-5147-4f5a-852c-0f415230ce2c"); - private static final Trace LOGGER = TraceManager.getTrace(TestIntegrationSecurity.class); - @Autowired private GuiProfiledPrincipalManager focusProfileService; private MidPointGuiAuthorizationEvaluator midPointGuiAuthorizationEvaluator; @@ -77,7 +63,8 @@ public class TestIntegrationSecurity extends AbstractInitializedGuiIntegrationTe public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - midPointGuiAuthorizationEvaluator = new MidPointGuiAuthorizationEvaluator(securityEnforcer, securityContextManager, taskManager); + midPointGuiAuthorizationEvaluator = new MidPointGuiAuthorizationEvaluator( + securityEnforcer, securityContextManager, taskManager); repoAddObjectFromFile(ROLE_UI_ALLOW_ALL_FILE, initResult); repoAddObjectFromFile(ROLE_UI_DENY_ALL_FILE, initResult); @@ -86,12 +73,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAdd(ROLE_AUTHORIZATION_2, initResult); } - // TODO: decide tests with anon user @Test public void test100DecideNoRole() throws Exception { - final String TEST_NAME = "test100DecideNoRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject user = getUser(USER_JACK_OID); @@ -117,7 +102,6 @@ public void test100DecideNoRole() throws Exception { @Test public void test110DecideRoleUiAllowAll() throws Exception { - final String TEST_NAME = "test110DecideRoleUiAllowAll"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UI_ALLOW_ALL_OID); @@ -144,7 +128,6 @@ public void test110DecideRoleUiAllowAll() throws Exception { @Test public void test120DecideRoleUiDenyAll() throws Exception { - final String TEST_NAME = "test120DecideRoleUiDenyAll"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UI_DENY_ALL_OID); @@ -175,7 +158,6 @@ public void test120DecideRoleUiDenyAll() throws Exception { */ @Test public void test200DecideRoleUiDenyAllow() throws Exception { - final String TEST_NAME = "test200DecideRoleUiDenyAllow"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UI_DENY_ALLOW_OID); @@ -206,8 +188,6 @@ public void test200DecideRoleUiDenyAllow() throws Exception { */ @Test public void test300ConflictingAuthorizationIds() throws Exception { - final String TEST_NAME = "test300ConflictingAuthorizationIds"; - // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_AUTHORIZATION_1.oid); @@ -226,25 +206,27 @@ public void test300ConflictingAuthorizationIds() throws Exception { private void assertAllow(Authentication authentication, String path) { try { - LOGGER.debug("*** Attempt to DECIDE {} (expected allow)", path); + logger.debug("*** Attempt to DECIDE {} (expected allow)", path); - midPointGuiAuthorizationEvaluator.decide(authentication, createFilterInvocation(path), createAuthConfigAttributes()); + midPointGuiAuthorizationEvaluator.decide( + authentication, createFilterInvocation(path), createAuthConfigAttributes()); display("DECIDE OK allowed access to " + path); } catch (AccessDeniedException e) { display("DECIDE WRONG failed to allowed access to " + path); - throw new AssertionError("Expected that access to "+path+" is allowed, but it was denied", e); + throw new AssertionError("Expected that access to " + path + " is allowed, but it was denied", e); } } private void assertDeny(Authentication authentication, String path) { try { - LOGGER.debug("*** Attempt to DECIDE {} (expected deny)", path); + logger.debug("*** Attempt to DECIDE {} (expected deny)", path); - midPointGuiAuthorizationEvaluator.decide(authentication, createFilterInvocation(path), createAuthConfigAttributes()); + midPointGuiAuthorizationEvaluator.decide( + authentication, createFilterInvocation(path), createAuthConfigAttributes()); display("DECIDE WRONG failed to deny access to " + path); - fail("Expected that access to "+path+" is denied, but it was allowed"); + fail("Expected that access to " + path + " is denied, but it was allowed"); } catch (AccessDeniedException e) { // expected display("DECIDE OK denied access to " + path); @@ -252,10 +234,12 @@ private void assertDeny(Authentication authentication, String path) { } - private Authentication createPasswordAuthentication(String username, Class focusType) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + private Authentication createPasswordAuthentication( + String username, Class focusType) + throws ObjectNotFoundException, SchemaException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { MidPointPrincipal principal = focusProfileService.getPrincipal(username, focusType); - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); - return auth; + return new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); } private FilterInvocation createFilterInvocation(String requestPath) { @@ -266,27 +250,10 @@ private Collection createAuthConfigAttributes() { return createConfigAttributes("fullyAuthenticated"); } - private Collection createConfigAttributes(String... actions) { - Collection configAttributes = new ArrayList<>(); - for (String action: actions) { - configAttributes.add(new ConfigAttribute() { - private static final long serialVersionUID = 1L; - - @Override - public String getAttribute() { - return action; - } - - @Override - public String toString() { - return action; - } - }); - } - return null; - } - - private void cleanupAutzTest(String userOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { + private void cleanupAutzTest(String userOid) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + PolicyViolationException, SecurityViolationException { login(userAdministrator); unassignAllRoles(userOid); } diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/LocalizationTest.java b/infra/common/src/test/java/com/evolveum/midpoint/common/LocalizationTest.java index 46a86c3a4b0..d49ac368c0e 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/LocalizationTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/LocalizationTest.java @@ -9,6 +9,7 @@ import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.LocalizableMessage; import com.evolveum.midpoint.util.LocalizableMessageBuilder; import org.testng.AssertJUnit; @@ -22,7 +23,7 @@ /** * Created by Viliam Repan (lazyman). */ -// TODO testing: missing from suite, 1 test failing +@UnusedTestElement("1 test failing, not in suite") public class LocalizationTest extends AbstractUnitTest { private static String midpointHome; diff --git a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java index 2ba894da3de..11babb0927b 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java @@ -7,10 +7,7 @@ package com.evolveum.midpoint.validator.test; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.io.FileInputStream; @@ -29,16 +26,13 @@ import com.evolveum.midpoint.common.validator.EventHandler; import com.evolveum.midpoint.common.validator.EventResult; import com.evolveum.midpoint.common.validator.LegacyValidator; -import com.evolveum.midpoint.prism.Objectable; -import com.evolveum.midpoint.prism.PrismContainer; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismProperty; -import com.evolveum.midpoint.prism.PrismPropertyDefinition; +import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.PrettyPrinter; @@ -49,7 +43,8 @@ * * @author Radovan Semancik */ -public class BasicValidatorTest extends AbstractUnitTest { +public class BasicValidatorTest extends AbstractUnitTest + implements OperationResultTestMixin { public static final String BASE_PATH = "src/test/resources/validator/"; private static final String OBJECT_RESULT_OPERATION_NAME = BasicValidatorTest.class.getName() + ".validateObject"; @@ -65,7 +60,7 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void resource1Valid() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".resource1Valid"); + OperationResult result = createOperationResult(); EventHandler handler = new EventHandler() { @Override @@ -82,9 +77,9 @@ public EventResult postMarshall(PrismObject object, El object.checkConsistence(); PrismContainer extensionContainer = object.getExtension(); - PrismProperty menProp = extensionContainer.findProperty(new ItemName("http://myself.me/schemas/whatever","menOnChest")); + PrismProperty menProp = extensionContainer.findProperty(new ItemName("http://myself.me/schemas/whatever", "menOnChest")); assertNotNull("No men on a dead man chest!", menProp); - assertEquals("Wrong number of men on a dead man chest", (Integer)15, menProp.getAnyRealValue()); + assertEquals("Wrong number of men on a dead man chest", (Integer) 15, menProp.getAnyRealValue()); PrismPropertyDefinition menPropDef = menProp.getDefinition(); assertNotNull("Men on a dead man chest NOT defined", menPropDef); assertEquals("Wrong type for men on a dead man chest definition", DOMUtil.XSD_INT, menPropDef.getTypeName()); @@ -104,7 +99,7 @@ public void handleGlobalError(OperationResult currentResult) { /* nothing */ } @Test public void handlerTest() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".handlerTest"); + OperationResult result = createOperationResult(); final List postMarshallHandledOids = new ArrayList<>(); final List preMarshallHandledOids = new ArrayList<>(); @@ -133,7 +128,7 @@ public void handleGlobalError(OperationResult currentResult) { }; - validateFile("three-objects.xml",handler,result); + validateFile("three-objects.xml", handler, result); System.out.println(result.debugDump()); AssertJUnit.assertTrue("Result is not success", result.isSuccess()); @@ -147,9 +142,9 @@ public void handleGlobalError(OperationResult currentResult) { @Test public void notWellFormed() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".notWellFormed"); + OperationResult result = createOperationResult(); - validateFile("not-well-formed.xml",result); + validateFile("not-well-formed.xml", result); System.out.println(result.debugDump()); AssertJUnit.assertFalse(result.isSuccess()); @@ -162,9 +157,9 @@ public void notWellFormed() throws Exception { @Test public void undeclaredPrefix() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".undeclaredPrefix"); + OperationResult result = createOperationResult(); - validateFile("undeclared-prefix.xml",result); + validateFile("undeclared-prefix.xml", result); System.out.println(result.debugDump()); AssertJUnit.assertFalse(result.isSuccess()); @@ -177,9 +172,9 @@ public void undeclaredPrefix() throws Exception { @Test public void schemaViolation() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".schemaViolation"); + OperationResult result = createOperationResult(); - validateFile("three-users-schema-violation.xml",result); + validateFile("three-users-schema-violation.xml", result); System.out.println(result.debugDump()); assertFalse(result.isSuccess()); @@ -196,7 +191,7 @@ public void schemaViolation() throws Exception { */ @Test public void testStopOnErrors() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".testStopOnErrors"); + OperationResult result = createOperationResult(); LegacyValidator validator = new LegacyValidator(PrismTestUtil.getPrismContext()); validator.setVerbose(false); @@ -206,14 +201,14 @@ public void testStopOnErrors() throws Exception { System.out.println(result.debugDump()); assertFalse(result.isSuccess()); - assertEquals(2,result.getSubresults().size()); + assertEquals(2, result.getSubresults().size()); } @Test public void noName() throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+".noName"); + OperationResult result = createOperationResult(); - validateFile("no-name.xml",result); + validateFile("no-name.xml", result); System.out.println(result.debugDump()); AssertJUnit.assertFalse(result.isSuccess()); @@ -223,12 +218,12 @@ public void noName() throws Exception { } private void validateFile(String filename, OperationResult result) throws FileNotFoundException { - validateFile(filename,(EventHandler) null,result); + validateFile(filename, (EventHandler) null, result); } - private void validateFile(String filename,EventHandler handler, OperationResult result) throws FileNotFoundException { + private void validateFile(String filename, EventHandler handler, OperationResult result) throws FileNotFoundException { LegacyValidator validator = new LegacyValidator(PrismTestUtil.getPrismContext()); - if (handler!=null) { + if (handler != null) { validator.setHandler(handler); } validator.setVerbose(false); diff --git a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeSkipSchemaValidationTest.java b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeSkipSchemaValidationTest.java index 76da331bce2..b84cdc0eba5 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeSkipSchemaValidationTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeSkipSchemaValidationTest.java @@ -8,14 +8,13 @@ package com.evolveum.midpoint.validator.test; import com.evolveum.midpoint.common.validator.LegacyValidator; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; - -// TODO testing: missing from suite, 3 tests failing - so what about that annotation? :-) +@UnusedTestElement("3 tests failing, not in suite") public class UnknownNodeSkipSchemaValidationTest extends UnknownNodeValidationTest { @Override protected void customizeValidator(LegacyValidator validator) { validator.setValidateSchema(false); } - } diff --git a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeValidationTest.java b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeValidationTest.java index bf92b0d683d..6ea4d74cde5 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeValidationTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/UnknownNodeValidationTest.java @@ -16,12 +16,14 @@ import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; // TODO testing: missing from suite, all passing -public class UnknownNodeValidationTest extends AbstractUnitTest { +public class UnknownNodeValidationTest extends AbstractUnitTest + implements OperationResultTestMixin { public static final String BASE_PATH = "src/test/resources/validator/unknown/"; private static final String OBJECT_RESULT_OPERATION_NAME = BasicValidatorTest.class.getName() + ".validateObject"; @@ -32,7 +34,6 @@ public void setup() throws SchemaException, SAXException, IOException { PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - @Test public void attributeInReference() throws Exception { validateNodeFailure("AttributeInReference", "reference-attribute.xml", @@ -89,8 +90,8 @@ public void elementInConnector() throws Exception { } protected void validateNodeFailure(String name, String file, String expected) throws Exception { - OperationResult result = new OperationResult(this.getClass().getName()+"." + name); - validateFile(file,result); + OperationResult result = createOperationResult(); + validateFile(file, result); System.out.println(result.debugDump()); AssertJUnit.assertFalse("Result should not be successful", result.isSuccess()); String message = result.getMessage(); @@ -99,12 +100,12 @@ protected void validateNodeFailure(String name, String file, String expected) th } protected void validateFile(String filename, OperationResult result) throws FileNotFoundException { - validateFile(filename,(EventHandler) null,result); + validateFile(filename, (EventHandler) null, result); } - protected void validateFile(String filename,EventHandler handler, OperationResult result) throws FileNotFoundException { + protected void validateFile(String filename, EventHandler handler, OperationResult result) throws FileNotFoundException { LegacyValidator validator = new LegacyValidator(PrismTestUtil.getPrismContext()); - if (handler!=null) { + if (handler != null) { validator.setHandler(handler); } validator.setVerbose(false); diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java index e3d1cf63b89..7eb26eed7d3 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java @@ -53,7 +53,6 @@ public class PrismTestUtil { private static final String OBJECT_TITLE_OUT_PREFIX = "\n*** "; private static final String OBJECT_TITLE_LOG_PREFIX = "*** "; - private static final String LOG_MESSAGE_PREFIX = ""; private static PrismContext prismContext; private static PrismContextFactory prismContextFactory; @@ -203,22 +202,6 @@ public static PolyStringType createPolyStringType(String orig, String norm) { return new PolyStringType(createPolyString(orig, norm)); } - // TODO inttest: replace with UnitTestMixin (TestUtil?) - public static void displayTestTitle(String testName) { - System.out.println("\n\n===[ "+testName+" ]===\n"); - LOGGER.info("===[ {} ]===",testName); - } - - public static void displayWhen(String testName) { - System.out.println("\n\n---[ "+testName+" WHEN ]---\n"); - LOGGER.info("---[ {} WHEN ]---",testName); - } - - public static void displayThen(String testName) { - System.out.println("\n\n---[ "+testName+" THEN ]---\n"); - LOGGER.info("---[ {} THEN ]---",testName); - } - public static SearchFilterType unmarshalFilter(File file) throws Exception { return prismContext.parserFor(file).parseRealValue(SearchFilterType.class); } @@ -230,13 +213,7 @@ public static ObjectFilter getFilterCondition(ObjectFilter filter, int index) { return ((LogicalFilter) filter).getConditions().get(index); } - public static void display(String title, String value) { - System.out.println(OBJECT_TITLE_OUT_PREFIX + title); - System.out.println(value); - LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" - + value); - } - + // TODO versions with external logger? public static void display(String title, DebugDumpable dumpable) { System.out.println(OBJECT_TITLE_OUT_PREFIX + title); System.out.println(dumpable == null ? "null" : dumpable.debugDump(1)); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/ItemImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/ItemImpl.java index b8ddfd3831a..c5544210fb4 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/ItemImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/ItemImpl.java @@ -79,7 +79,7 @@ public abstract class ItemImpl e protected PrismContainerValue parent; protected D definition; @NotNull protected final List values = new ArrayList<>(); - private transient Map userData = new HashMap<>();; + private transient Map userData = new HashMap<>(); protected EquivalenceStrategy defaultEquivalenceStrategy; diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/AbstractPrismTest.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/AbstractPrismTest.java index 7ddcaf24f5a..18d6be34103 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/AbstractPrismTest.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/AbstractPrismTest.java @@ -50,10 +50,6 @@ public void initPrismContext() throws SchemaException, SAXException, IOException PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - protected void display(String title, String value) { - PrismTestUtil.display(title, value); - } - protected void display(String title, DebugDumpable value) { PrismTestUtil.display(title, value); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java index b8f8f2fb13e..4b8fbd4251a 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java @@ -19,6 +19,7 @@ import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -52,4 +53,12 @@ public void setup() throws SchemaException, SAXException, IOException { protected PrismObjectDefinition getUserDefinition() { return getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } + + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java index 776d155bb27..49fc0d62ab0 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java @@ -7,6 +7,25 @@ package com.evolveum.midpoint.schema; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.prism.util.PrismTestUtil.*; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_OWNER_REF; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import javax.xml.namespace.QName; + +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.NotNull; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.ParentPathSegment; @@ -24,35 +43,14 @@ import com.evolveum.midpoint.util.DomAsserts; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.query_3.PagingType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -import org.apache.commons.io.FileUtils; -import org.jetbrains.annotations.NotNull; -import org.testng.AssertJUnit; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import javax.xml.namespace.QName; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import static com.evolveum.midpoint.prism.util.PrismTestUtil.*; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_OWNER_REF; -import static org.testng.AssertJUnit.*; public class TestQueryConverter extends AbstractUnitTest { - private static final Trace LOGGER = TraceManager.getTrace(TestQueryConverter.class); - private static final File TEST_DIR = new File("src/test/resources/queryconverter"); private static final String NS_EXTENSION = "http://midpoint.evolveum.com/xml/ns/test/extension"; @@ -152,7 +150,7 @@ public void testAccountQueryAttributesAndResource() throws Exception { PrismAsserts.assertEqualsFilterValue((EqualFilter) second, "uid=jbond,ou=People,dc=example,dc=com"); QueryType convertedQueryType = toQueryType(query); - LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); + logger.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); } @Test @@ -210,7 +208,7 @@ public void testAccountQueryCompositeOr() throws Exception { assertRefFilterValue((RefFilter) forth, "d0db5be9-cb93-401f-b6c1-86ffffe4cd5e"); QueryType convertedQueryType = toQueryType(query); - LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); + logger.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); } @Test @@ -230,13 +228,13 @@ public void testConnectorQuery() throws Exception { QueryType convertedQueryType = toQueryType(query); displayQueryType(convertedQueryType); } catch (Exception ex) { - LOGGER.error("Error while converting query: {}", ex.getMessage(), ex); + logger.error("Error while converting query: {}", ex.getMessage(), ex); throw ex; } } - private PrismObjectDefinition getUserDefinition(){ + private PrismObjectDefinition getUserDefinition() { return getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } @@ -263,7 +261,7 @@ public void testTypeFilterQuery() throws Exception { QueryType convertedQueryType = toQueryType(query); displayQueryType(convertedQueryType); } catch (Exception ex) { - LOGGER.error("Error while converting query: {}", ex.getMessage(), ex); + logger.error("Error while converting query: {}", ex.getMessage(), ex); throw ex; } @@ -291,7 +289,7 @@ public void testShadowKindTypeQuery() throws Exception { displayQueryType(convertedQueryType); } catch (Exception ex) { - LOGGER.error("Error while converting query: {}", ex.getMessage(), ex); + logger.error("Error while converting query: {}", ex.getMessage(), ex); throw ex; } @@ -376,20 +374,20 @@ public void testUserQuery() throws Exception { // prismContext.silentMarshalObject(queryTypeNew, LOGGER); for (File file : userQueriesToTest) { SearchFilterType filterType = PrismTestUtil.parseAtomicValue(file, SearchFilterType.COMPLEX_TYPE); - LOGGER.info("===[ query type parsed ]==="); + logger.info("===[ query type parsed ]==="); ObjectQuery query; try { query = getQueryConverter().createObjectQuery(UserType.class, filterType); - LOGGER.info("query converted: "); + logger.info("query converted: "); - LOGGER.info("QUERY DUMP: {}", query.debugDump()); - LOGGER.info("QUERY Pretty print: {}", query.toString()); + logger.info("QUERY DUMP: {}", query.debugDump()); + logger.info("QUERY Pretty print: {}", query.toString()); System.out.println("QUERY Pretty print: " + query.toString()); QueryType convertedQueryType = getQueryConverter().createQueryType(query); - LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); + logger.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()))); } catch (Exception ex) { - LOGGER.error("Error while converting query: {}", ex.getMessage(), ex); + logger.error("Error while converting query: {}", ex.getMessage(), ex); throw ex; } } @@ -404,8 +402,8 @@ public void testConvertQueryNullFilter() throws Exception { assertNull(queryType.getFilter()); PagingType paging = queryType.getPaging(); assertNotNull(paging); - assertEquals(new Integer(0), paging.getOffset()); - assertEquals(new Integer(10), paging.getMaxSize()); + assertEquals(Integer.valueOf(0), paging.getOffset()); + assertEquals(Integer.valueOf(10), paging.getMaxSize()); } @@ -431,7 +429,7 @@ private void checkQuery(Class objectClass, ObjectQuery displayQueryType(q2jaxb); ObjectQuery q2object = toObjectQuery(objectClass, q2jaxb); assertEquals("Reparsed query is not as original one (via toString)", q1object.toString(), q2object.toString()); // primitive way of comparing parsed queries - assertTrue("Reparsed query is not as original one (via equivalent):\nq1="+q1object+"\nq2="+q2object, q1object.equivalent(q2object)); + assertTrue("Reparsed query is not as original one (via equivalent):\nq1=" + q1object + "\nq2=" + q2object, q1object.equivalent(q2object)); } private void checkQueryRoundtrip(Class objectClass, ObjectQuery q1object, String q2xml) throws Exception { @@ -556,13 +554,13 @@ public void test360Ref() throws Exception { displayQueryType(q2jaxb); ObjectQuery q2object = toObjectQuery(ShadowType.class, q2jaxb); - System.out.println("q1object:\n"+q1object.debugDump(1)); - System.out.println("q2object:\n"+q2object.debugDump(1)); + System.out.println("q1object:\n" + q1object.debugDump(1)); + System.out.println("q2object:\n" + q2object.debugDump(1)); assertEquals("Reparsed query is not as original one (via toString)", q1object.toString(), q2object.toString()); // primitive way of comparing parsed queries if (!q1object.equivalent(q2object)) { - AssertJUnit.fail("Reparsed query is not as original one (via equivalent):\nq1="+q1object+"\nq2="+q2object); + AssertJUnit.fail("Reparsed query is not as original one (via equivalent):\nq1=" + q1object + "\nq2=" + q2object); } } @@ -645,17 +643,17 @@ public void test510InOidContainer() throws Exception { public void test590Logicals() throws Exception { ObjectQuery q = getPrismContext().queryFor(UserType.class) .block() - .all() - .or().none() - .or().undefined() + .all() + .or().none() + .or().undefined() .endBlock() .and().none() .and() - .not() - .block() - .all() - .and().undefined() - .endBlock() + .not() + .block() + .all() + .and().undefined() + .endBlock() .build(); checkQueryRoundtripFile(UserType.class, q); } @@ -668,11 +666,11 @@ public void test595Logicals2() throws Exception { .or().item(UserType.F_DESCRIPTION).eq("C") .and().item(UserType.F_DESCRIPTION).eq("D") .and() - .block() - .item(UserType.F_DESCRIPTION).eq("E1") - .and().item(UserType.F_DESCRIPTION).eq("E2") - .or().item(UserType.F_DESCRIPTION).eq("E3") - .endBlock() + .block() + .item(UserType.F_DESCRIPTION).eq("E1") + .and().item(UserType.F_DESCRIPTION).eq("E2") + .or().item(UserType.F_DESCRIPTION).eq("E3") + .endBlock() .build(); checkQueryRoundtripFile(UserType.class, q); @@ -682,7 +680,7 @@ public void test595Logicals2() throws Exception { public void test600Type() throws Exception { ObjectQuery q = getPrismContext().queryFor(ObjectType.class) .type(UserType.class) - .item(UserType.F_NAME).eqPoly("somename", "somename") + .item(UserType.F_NAME).eqPoly("somename", "somename") .build(); checkQueryRoundtripFile(ObjectType.class, q); } @@ -692,12 +690,12 @@ public void test700Exists() throws Exception { PrismReferenceValue ownerRef = ObjectTypeUtil.createObjectRef("1234567890", ObjectTypes.USER).asReferenceValue(); ObjectQuery q = getPrismContext().queryFor(AccessCertificationCaseType.class) .exists(new ParentPathSegment()) // if using T_PARENT then toString representation of paths is different - .block() - .id(123456L) - .or().item(F_OWNER_REF).ref(ownerRef) - .endBlock() + .block() + .id(123456L) + .or().item(F_OWNER_REF).ref(ownerRef) + .endBlock() .and().exists(AccessCertificationCaseType.F_WORK_ITEM) - .item(AccessCertificationWorkItemType.F_STAGE_NUMBER).eq(3) + .item(AccessCertificationWorkItemType.F_STAGE_NUMBER).eq(3) .build(); checkQueryRoundtripFile(AccessCertificationCaseType.class, q); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java index 8f1fb352996..2bd14c541c4 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java @@ -23,7 +23,6 @@ import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.ObjectTypes; -import static com.evolveum.midpoint.prism.util.PrismTestUtil.display; import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; import static java.util.Arrays.asList; import static java.util.Collections.singleton; @@ -39,8 +38,6 @@ public class TestSchemaDelta extends AbstractSchemaTest { @Test public void testAssignmentNullIdApplyToObject() throws Exception { - final String TEST_NAME = "testAssignmentNullIdApplyToObject"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); @@ -65,8 +62,6 @@ public void testAssignmentNullIdApplyToObject() throws Exception { @Test public void testAddInducementNullIdApplyToObject() throws Exception { - final String TEST_NAME = "testAddInducementNullIdApplyToObject"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -91,8 +86,6 @@ public void testAddInducementNullIdApplyToObject() throws Exception { @Test public void testDeleteInducementValidIdSameValueApplyToObject() throws Exception { - final String TEST_NAME = "testDeleteInducementValidIdSameValueApplyToObject"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -122,8 +115,6 @@ public void testDeleteInducementValidIdSameValueApplyToObject() throws Exception @Test public void testDeleteInducementValidIdEmptyValueApplyToObject() throws Exception { - final String TEST_NAME = "testDeleteInducementValidIdEmptyValueApplyToObject"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -148,8 +139,6 @@ public void testDeleteInducementValidIdEmptyValueApplyToObject() throws Exceptio @Test public void testDeleteInducementValidIdEmptyValueApplyToObjectStatic() throws Exception { - final String TEST_NAME = "testDeleteInducementValidIdEmptyValueApplyToObjectStatic"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); System.out.println("Role before delta application:"); @@ -176,8 +165,6 @@ public void testDeleteInducementValidIdEmptyValueApplyToObjectStatic() throws Ex @Test public void testDeleteInducementConstructionSameNullIdApplyToObject() throws Exception { - final String TEST_NAME = "testDeleteInducementConstructionSameNullIdApplyToObject"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -214,8 +201,6 @@ public void testDeleteInducementConstructionSameNullIdApplyToObject() throws Exc @Test public void testDeleteInducementActivationSameNullIdApplyToObject() throws Exception { - final String TEST_NAME = "testDeleteInducementActivationSameNullIdApplyToObject"; - // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -248,8 +233,6 @@ public void testDeleteInducementActivationSameNullIdApplyToObject() throws Excep @Test public void testDeleteUserAssignmentActivationSameNullIdApplyToObject() throws Exception { - final String TEST_NAME = "testDeleteUserAssignmentActivationSameNullIdApplyToObject"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); @@ -286,8 +269,6 @@ public void testDeleteUserAssignmentActivationSameNullIdApplyToObject() throws E @Test public void testAddAssignmentSameOidDifferentTargetType() throws Exception { - final String TEST_NAME = "testAddAssignmentSameOidDifferentTargetType"; - // GIVEN PrismObject user = new UserType(getPrismContext()) .name("test") @@ -315,8 +296,6 @@ public void testAddAssignmentSameOidDifferentTargetType() throws Exception { // subtract of single-valued PCV from multivalued one @Test public void testSubtractAssignmentFromAddDelta() throws Exception { - final String TEST_NAME = "testSubtractAssignmentFromAddDelta"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_BILL_FILE); ObjectDelta addDelta = DeltaFactory.Object.createAddDelta(user); @@ -348,8 +327,6 @@ public void testSubtractAssignmentFromAddDelta() throws Exception { @Test public void testSubtractAssignmentFromModifyDelta() throws Exception { - final String TEST_NAME = "testSubtractAssignmentFromModifyDelta"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_BILL_FILE); user.asObjectable().getAssignment().get(0).setId(9999L); @@ -388,8 +365,6 @@ public void testSubtractAssignmentFromModifyDelta() throws Exception { // subtract of single-valued PCV from multivalued one @Test public void testFactorAddDeltaForItem() throws Exception { - final String TEST_NAME = "testFactorAddDeltaForItem"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_BILL_FILE); String OID = "user-oid-1"; @@ -421,8 +396,6 @@ private void assertDeltaOid(ObjectDelta delta, String expectedOid) { // subtract of single-valued PCV from multivalued one @Test public void testFactorAddDeltaForItems() throws Exception { - final String TEST_NAME = "testFactorAddDeltaForItems"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_BILL_FILE); String OID = "user-oid-1"; @@ -448,8 +421,6 @@ public void testFactorAddDeltaForItems() throws Exception { @Test public void testFactorAddDeltaForItemValues() throws Exception { - final String TEST_NAME = "testFactorAddDeltaForItemValues"; - // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_BILL_FILE); String OID = "user-oid-1"; @@ -477,8 +448,6 @@ public void testFactorAddDeltaForItemValues() throws Exception { @Test public void testFactorModifyDeltaForItem() throws Exception { - final String TEST_NAME = "testFactorModifyDeltaForItem"; - // GIVEN String OID = "oid1"; ObjectDelta delta = getPrismContext().deltaFor(UserType.class) @@ -508,8 +477,6 @@ public void testFactorModifyDeltaForItem() throws Exception { @Test public void testFactorModifyDeltaForItemValues() throws Exception { - final String TEST_NAME = "testFactorModifyDeltaForItemValues"; - // GIVEN String OID = "oid1"; ObjectDelta delta = getPrismContext().deltaFor(UserType.class) @@ -556,9 +523,7 @@ public void testFactorModifyDeltaForItemValues() throws Exception { */ @Test // MID-4690 public void testObjectDeltaUnion() throws Exception { - final String TEST_NAME="testObjectDeltaUnion"; // GIVEN - ProtectedStringType value = new ProtectedStringType(); value.setClearValue("hi"); PasswordType newPassword = new PasswordType(getPrismContext()).value(value); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractContainerValueParserTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractContainerValueParserTest.java index 981c71ac122..7afe2b7282e 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractContainerValueParserTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractContainerValueParserTest.java @@ -17,8 +17,8 @@ /** * @author mederly */ -public abstract class AbstractContainerValueParserTest extends - AbstractPrismValueParserTest> { +public abstract class AbstractContainerValueParserTest + extends AbstractPrismValueParserTest> { @SuppressWarnings("Convert2MethodRef") protected void processParsings(Class clazz, Class specificClass, QName type, QName specificType, SerializingFunction> serializer, String serId) throws Exception { diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractParserTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractParserTest.java index 5b4f7f5b2a3..3bb452b5a56 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractParserTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/AbstractParserTest.java @@ -7,27 +7,29 @@ package com.evolveum.midpoint.schema.parser; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.SchemaException; +import static com.evolveum.midpoint.schema.TestConstants.COMMON_DIR_PATH; + +import java.io.File; +import java.io.IOException; + import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.xml.sax.SAXException; -import java.io.File; -import java.io.IOException; - -import static com.evolveum.midpoint.schema.TestConstants.COMMON_DIR_PATH; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.schema.MidPointPrismContextFactory; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.tools.testng.AbstractUnitTest; +import com.evolveum.midpoint.util.PrettyPrinter; +import com.evolveum.midpoint.util.exception.SchemaException; /** * @author mederly */ -public abstract class AbstractParserTest { +public abstract class AbstractParserTest extends AbstractUnitTest { protected String language; protected boolean namespaces; @@ -47,18 +49,13 @@ public void temp(@Optional String language, @Optional Boolean namespaces) { } protected File getFile(String baseName) { - return new File(COMMON_DIR_PATH + "/" + language + "/" + (namespaces ? "ns":"no-ns"), + return new File(COMMON_DIR_PATH + "/" + language + "/" + (namespaces ? "ns" : "no-ns"), baseName + "." + language); } - protected void displayTestTitle(String testName) { - PrismTestUtil.displayTestTitle(testName + " (" + language + ", " + (namespaces ? "with" : "no") + " namespaces)"); - } - protected abstract File getFile(); protected PrismContext getPrismContext() { return PrismTestUtil.getPrismContext(); } - } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseApprovalContext.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseApprovalContext.java index 9e5846255cc..dcbb87f05a2 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseApprovalContext.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseApprovalContext.java @@ -32,15 +32,11 @@ protected File getFile() { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - - //processParsings(v -> getPrismContext().serializerFor(language).serialize(v)); // no item name nor definition => cannot serialize processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serializeRealValue(v.asContainerable()), "s3"); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java index 225cd2cdbd0..f142600bea1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java @@ -37,15 +37,11 @@ protected File getFile() { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - - //processParsings(v -> getPrismContext().serializerFor(language).serialize(v)); // no item name nor definition => cannot serialize processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name processParsings(v -> getPrismContext().serializerFor(language).serializeRealValue(v.asContainerable()), "s3"); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java index f2299a37a43..ff1fa557770 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java @@ -46,21 +46,17 @@ public void testParseToXNode() throws Exception { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsingsPCV(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test @SuppressWarnings("Duplicates") public void testParseRoundTripAsPCV() throws Exception{ - displayTestTitle("testParseRoundTripAsPCV"); - processParsingsPCV(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_SYSTEM_CONFIGURATION).serialize(v), "s2"); // misleading item name @@ -71,8 +67,6 @@ public void testParseRoundTripAsPCV() throws Exception{ @Test @SuppressWarnings("Duplicates") public void testParseRoundTripAsPO() throws Exception{ - displayTestTitle("testParseRoundTripAsPO"); - processParsingsPO(v -> getPrismContext().serializerFor(language).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1", false); processParsingsPO(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_SYSTEM_CONFIGURATION).serialize(v), "s2", false); // misleading item name diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java index 1e76593f926..9bac80055dc 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java @@ -29,15 +29,11 @@ protected File getFile() { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - - //processParsings(v -> getPrismContext().serializerFor(language).serialize(v)); // no item name nor definition => cannot serialize processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serializeRealValue(v.asContainerable()), "s3"); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java index 03681f29ab2..632902888a1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java @@ -39,14 +39,11 @@ protected File getFile() { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseSerialize() throws Exception{ - displayTestTitle("testParseSerialize"); - PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); PrismContainerValue mappingPval = parser.parseItemValue(); @@ -67,8 +64,6 @@ public void testParseSerialize() throws Exception{ @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java index 873175b48c6..cff5667681e 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java @@ -30,15 +30,11 @@ protected File getFile() { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - - //processParsings(v -> getPrismContext().serializerFor(language).serialize(v)); // no item name nor definition => cannot serialize processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serializeRealValue(v.asContainerable()), "s3"); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java index 740610d4428..bfc79505e26 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java @@ -41,20 +41,16 @@ protected File getFile() { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsingsPCV(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test public void testParseRoundTripAsPCV() throws Exception{ - displayTestTitle("testParseRoundTripAsPCV"); - processParsingsPCV(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_SYSTEM_CONFIGURATION).serialize(v), "s2"); // misleading item name @@ -64,8 +60,6 @@ public void testParseRoundTripAsPCV() throws Exception{ @Test public void testParseRoundTripAsPO() throws Exception{ - displayTestTitle("testParseRoundTripAsPO"); - processParsingsPO(v -> getPrismContext().serializerFor(language).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1", false); processParsingsPO(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_SYSTEM_CONFIGURATION).serialize(v), "s2", false); // misleading item name diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjects.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjects.java index ddc8a86c6a1..4b8850cdd3c 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjects.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjects.java @@ -35,7 +35,6 @@ protected File getFile() { @Test public void testRoundTrip() throws Exception { - displayTestTitle("testRoundTrip"); PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIteratively.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIteratively.java index b45718201e7..a33cfc5441f 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIteratively.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIteratively.java @@ -34,7 +34,6 @@ protected File getFile() { @Test public void testRoundTrip() throws Exception { - displayTestTitle("testRoundTrip"); PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyFirstTwo.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyFirstTwo.java index b69b2c04ba2..4040a4edaf8 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyFirstTwo.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyFirstTwo.java @@ -33,7 +33,6 @@ protected File getFile() { @Test public void testRoundTrip() throws Exception { - displayTestTitle("testRoundTrip"); PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyWrong.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyWrong.java index 1713343d4cd..04b756317a6 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyWrong.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseObjectsIterativelyWrong.java @@ -37,7 +37,6 @@ protected File getFile() { @Test public void testParse() throws Exception { - displayTestTitle("testParse"); PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java index 87ee870b134..b10260d53a1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java @@ -62,8 +62,6 @@ protected File getFile() { @Test public void testParseResourceFile() throws Exception { - displayTestTitle("testParseResourceFile"); - // GIVEN PrismContext prismContext = getPrismContext(); @@ -79,8 +77,6 @@ public void testParseResourceFile() throws Exception { @Test public void testParseResourceFileSimple() throws Exception { - displayTestTitle("testParseResourceFileSimple"); - // GIVEN PrismContext prismContext = getPrismContext(); @@ -96,19 +92,16 @@ public void testParseResourceFileSimple() throws Exception { @Test public void testParseResourceRoundtripXml() throws Exception { - displayTestTitle("testParseResourceRoundtripXml"); doTestParseResourceRoundtrip(PrismContext.LANG_XML); } @Test public void testParseResourceRoundtripJson() throws Exception { - displayTestTitle("testParseResourceRoundtripJson"); doTestParseResourceRoundtrip(PrismContext.LANG_JSON); } @Test public void testParseResourceRoundtripYaml() throws Exception { - displayTestTitle("testParseResourceRoundtripYaml"); doTestParseResourceRoundtrip(PrismContext.LANG_YAML); } @@ -168,8 +161,6 @@ private void doTestParseResourceRoundtrip(String serializeInto) throws Exception */ @Test public void testSchemaRoundtrip() throws Exception { - displayTestTitle("testSchemaRoundtrip"); - // GIVEN PrismContext prismContext = getPrismContext(); @@ -284,19 +275,16 @@ private void assertResourceExpression(PrismObject resource, PrismC @Test public void testParseResourceExpressionRoundtripXml() throws Exception { - displayTestTitle("testParseResourceExpressionRoundtripXml"); doTestParseResourceExpressionRoundtrip(PrismContext.LANG_XML); } @Test public void testParseResourceExpressionRoundtripJson() throws Exception { - displayTestTitle("testParseResourceExpressionRoundtripJson"); doTestParseResourceExpressionRoundtrip(PrismContext.LANG_JSON); } @Test public void testParseResourceExpressionRoundtripYaml() throws Exception { - displayTestTitle("testParseResourceExpressionRoundtripYaml"); doTestParseResourceExpressionRoundtrip(PrismContext.LANG_YAML); } @@ -654,8 +642,6 @@ public void testParseResourceDomSimple() throws Exception { if (!"xml".equals(language)) { return; } - displayTestTitle("testParseResourceDomSimple"); - // GIVEN PrismContext prismContext = getPrismContext(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptOutput.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptOutput.java index 5d3ca5ccb3b..a1d8bd30bba 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptOutput.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptOutput.java @@ -35,10 +35,6 @@ protected File getFile() { @Test public void testParseToXNode() throws Exception { - displayTestTitle("testParseToXNode"); - - System.out.println("\n\n-----------------------------------\n"); - String file = MiscUtil.readFile(getFile()); System.out.println("Original text:\n" + file); @@ -52,14 +48,11 @@ public void testParseToXNode() throws Exception { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception { - displayTestTitle("testParseRoundTrip"); - processParsings(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpression.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpression.java index ee18523872e..92496022951 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpression.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpression.java @@ -14,7 +14,6 @@ import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ActionExpressionType; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ExpressionPipelineType; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ExpressionSequenceType; @@ -41,8 +40,7 @@ protected File getFile() { @Test public void testParseToXNode() throws Exception { - displayTestTitle("testParseToXNode"); - ItemDefinition sequenceDef = getPrismContext().getSchemaRegistry().findItemDefinitionByElementName(SchemaConstants.S_SEQUENCE); + ItemDefinition sequenceDef = getPrismContext().getSchemaRegistry().findItemDefinitionByElementName(SchemaConstants.S_SEQUENCE); System.out.println("sequence.substitutionHead = " + sequenceDef.getSubstitutionHead()); System.out.println("sequence.heterogeneousListItem = " + sequenceDef.isHeterogeneousListItem()); ComplexTypeDefinition sequenceCtd = getPrismContext().getSchemaRegistry().findComplexTypeDefinitionByType(sequenceDef.getTypeName()); @@ -63,14 +61,11 @@ public void testParseToXNode() throws Exception { @Test public void testParseFile() throws Exception { - displayTestTitle("testParseFile"); processParsings(null, null); } @Test public void testParseRoundTrip() throws Exception{ - displayTestTitle("testParseRoundTrip"); - processParsings(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name @@ -79,13 +74,13 @@ public void testParseRoundTrip() throws Exception{ } private void processParsings(SerializingFunction> serializer, String serId) throws Exception { - PrismPropertyDefinition definition = getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(SchemaConstants.S_PIPELINE); + PrismPropertyDefinition definition = getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(SchemaConstants.S_PIPELINE); processParsings(ExpressionPipelineType.class, ExpressionPipelineType.COMPLEX_TYPE, definition, serializer, serId); } @SuppressWarnings("unchecked") @Override - protected void assertPrismPropertyValueLocal(PrismPropertyValue value) throws SchemaException { + protected void assertPrismPropertyValueLocal(PrismPropertyValue value) { ExpressionPipelineType pipe = value.getValue(); JAXBElement sequenceJaxb1 = (JAXBElement) pipe.getScriptingExpression().get(0); assertEquals("Wrong element name (1)", SchemaConstants.S_SEQUENCE, sequenceJaxb1.getName()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpressionXsiType.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpressionXsiType.java index e9049cd90d5..84dc29016fb 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpressionXsiType.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseScriptingExpressionXsiType.java @@ -40,8 +40,6 @@ protected File getFile() { @Test public void testYamlSerialization() throws Exception { - displayTestTitle("testParseToXNode"); - String file = MiscUtil.readFile(getFile()); System.out.println("Original text:\n" + file); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java index e24812825f7..b19109e121f 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java @@ -37,20 +37,16 @@ protected File getFile() { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsings(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test public void testParseRoundTripAsPCV() throws Exception{ - displayTestTitle("testParseRoundTripAsPCV"); - processParsings(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name @@ -60,8 +56,6 @@ public void testParseRoundTripAsPCV() throws Exception{ @Test public void testParseRoundTripAsPO() throws Exception{ - displayTestTitle("testParseRoundTripAsPO"); - processParsingsPO(v -> getPrismContext().serializerFor(language).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1", false); processParsingsPO(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2", false); // misleading item name diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseSystemConfiguration.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseSystemConfiguration.java index b2d3901c496..470e52eafea 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseSystemConfiguration.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseSystemConfiguration.java @@ -47,21 +47,17 @@ public void testParseToXNode() throws Exception { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsingsPCV(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test @SuppressWarnings("Duplicates") public void testParseRoundTripAsPCV() throws Exception{ - displayTestTitle("testParseRoundTripAsPCV"); - processParsingsPCV(v -> getPrismContext().serializerFor(language).serialize(v), "s0"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsingsPCV(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name @@ -72,8 +68,6 @@ public void testParseRoundTripAsPCV() throws Exception{ @Test @SuppressWarnings("Duplicates") public void testParseRoundTripAsPO() throws Exception{ - displayTestTitle("testParseRoundTripAsPO"); - processParsingsPO(v -> getPrismContext().serializerFor(language).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1", false); processParsingsPO(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2", false); // misleading item name diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java index 5a8752f3bde..a8c12270fe6 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java @@ -47,20 +47,16 @@ protected File getFile() { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsingsPCV(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test public void testParseRoundTripAsPCV() throws Exception{ - displayTestTitle("testParseRoundTripAsPCV"); - SerializationOptions o = SerializationOptions.createSerializeReferenceNames(); processParsingsPCV(v -> getPrismContext().serializerFor(language).options(o).serialize(v), "s0"); processParsingsPCV(v -> getPrismContext().serializerFor(language).options(o).root(new QName("dummy")).serialize(v), "s1"); @@ -71,8 +67,6 @@ public void testParseRoundTripAsPCV() throws Exception{ @Test public void testParseRoundTripAsPO() throws Exception{ - displayTestTitle("testParseRoundTripAsPO"); - SerializationOptions o = SerializationOptions.createSerializeReferenceNames(); processParsingsPO(v -> getPrismContext().serializerFor(language).options(o).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).options(o).root(new QName("dummy")).serialize(v), "s1", false); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUserPolyString.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUserPolyString.java index d0ce369cc5c..8e5589d3949 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUserPolyString.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUserPolyString.java @@ -44,20 +44,16 @@ protected File getFile() { @Test public void testParseFileAsPCV() throws Exception { - displayTestTitle("testParseFileAsPCV"); processParsingsPCV(null, null); } @Test public void testParseFileAsPO() throws Exception { - displayTestTitle("testParseFileAsPO"); processParsingsPO(null, null, true); } @Test public void testParseRoundTripAsPCV() throws Exception { - displayTestTitle("testParseRoundTripAsPCV"); - SerializationOptions o = SerializationOptions.createSerializeReferenceNames(); processParsingsPCV(v -> getPrismContext().serializerFor(language).options(o).serialize(v), "s0"); processParsingsPCV(v -> getPrismContext().serializerFor(language).options(o).root(new QName("dummy")).serialize(v), "s1"); @@ -72,8 +68,6 @@ public void testParseRoundTripAsPCV() throws Exception { @Test public void testParseRoundTripAsPO() throws Exception { - displayTestTitle("testParseRoundTripAsPO"); - SerializationOptions o = SerializationOptions.createSerializeReferenceNames(); processParsingsPO(v -> getPrismContext().serializerFor(language).options(o).serialize(v), "s0", true); processParsingsPO(v -> getPrismContext().serializerFor(language).options(o).root(new QName("dummy")).serialize(v), "s1", diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java index 77a3861be84..b316f5254d5 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java @@ -130,8 +130,6 @@ public void testResourceSchemaJaxbRoundTrip() throws SchemaException { // WHEN -// JAXBElement resourceElement = new JAXBElement(SchemaConstants.C_RESOURCE, ResourceType.class, resource); -// String marshalledResource = PrismTestUtil.marshalElementToString(resourceElement); String marshalledResource = PrismTestUtil.serializeObjectToString(resource.asPrismObject()); System.out.println("Marshalled resource"); @@ -357,13 +355,13 @@ private void assertCapabilities(ResourceType resourceType) throws SchemaExceptio assertNotNull("null native capabilities", resourceType.getCapabilities().getNative()); assertFalse("empty native capabilities", resourceType.getCapabilities().getNative().getAny().isEmpty()); - assertEquals("Unexepected number of native capabilities", 3, resourceType.getCapabilities().getNative().getAny().size()); + assertEquals("Unexpected number of native capabilities", 3, resourceType.getCapabilities().getNative().getAny().size()); assertNotNull("null configured capabilities", resourceType.getCapabilities().getConfigured()); assertFalse("empty configured capabilities", resourceType.getCapabilities().getConfigured().getAny().isEmpty()); - assertEquals("Unexepected number of configured capabilities", 2, resourceType.getCapabilities().getConfigured().getAny().size()); + assertEquals("Unexpected number of configured capabilities", 2, resourceType.getCapabilities().getConfigured().getAny().size()); - assertEquals("Unexepected number of effective capabilities", 3, effectiveCapabilities.size()); + assertEquals("Unexpected number of effective capabilities", 3, effectiveCapabilities.size()); assertNotNull("No credentials effective capability", ResourceTypeUtil.getEffectiveCapability(resourceType, CredentialsCapabilityType.class)); assertNotNull("No activation effective capability", diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java index e2c0f904d23..26b5c1fd0e3 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java @@ -45,7 +45,7 @@ public void startTestContext(ITestResult testResult) { public void finishTestContext(ITestResult testResult) { SimpleMidpointTestContext context = SimpleMidpointTestContext.get(); SimpleMidpointTestContext.destroy(); - displayDefaultTestFooter(context.getTestName(), testResult); + displayTestFooter(context.getTestName(), testResult); } @Override diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java index 54e6edceee1..4f197bcfbf2 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java @@ -6,45 +6,33 @@ */ package com.evolveum.midpoint.test.util; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.util.QNameUtil; - import org.apache.commons.lang.StringUtils; import org.testng.AssertJUnit; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ public class MidPointAsserts { public static AssignmentType assertAssigned(PrismObject user, String targetOid, QName refType) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (refType.equals(targetRef.getType())) { @@ -54,13 +42,13 @@ public static AssignmentType assertAssigned(Pri } } } - AssertJUnit.fail(user + " does not have assigned "+refType.getLocalPart()+" "+targetOid); + AssertJUnit.fail(user + " does not have assigned " + refType.getLocalPart() + " " + targetOid); return null; // not reachable } public static void assertAssigned(PrismObject focus, String targetOid, QName refType, QName relation) { FocusType focusType = focus.asObjectable(); - for (AssignmentType assignmentType: focusType.getAssignment()) { + for (AssignmentType assignmentType : focusType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (refType.equals(targetRef.getType())) { @@ -71,12 +59,12 @@ public static void assertAssigned(PrismObject focus, String } } } - AssertJUnit.fail(focus + " does not have assigned "+refType.getLocalPart()+" "+targetOid+ ", relation "+relation); + AssertJUnit.fail(focus + " does not have assigned " + refType.getLocalPart() + " " + targetOid + ", relation " + relation); } public static AssignmentType assertInduced(PrismObject user, String targetOid, QName refType) { R userType = user.asObjectable(); - for (AssignmentType inducementType: userType.getInducement()) { + for (AssignmentType inducementType : userType.getInducement()) { ObjectReferenceType targetRef = inducementType.getTargetRef(); if (targetRef != null) { if (refType.equals(targetRef.getType())) { @@ -86,18 +74,18 @@ public static AssignmentType assertInduced(PrismObj } } } - AssertJUnit.fail(user + " does not have assigned "+refType.getLocalPart()+" "+targetOid); + AssertJUnit.fail(user + " does not have assigned " + refType.getLocalPart() + " " + targetOid); return null; // not reachable } public static void assertNotAssigned(PrismObject user, String targetOid, QName refType) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (QNameUtil.match(refType, targetRef.getType())) { if (targetOid.equals(targetRef.getOid())) { - AssertJUnit.fail(user + " does have assigned "+refType.getLocalPart()+" "+targetOid+" while not expecting it"); + AssertJUnit.fail(user + " does have assigned " + refType.getLocalPart() + " " + targetOid + " while not expecting it"); } } } @@ -106,13 +94,13 @@ public static void assertNotAssigned(PrismObject user, public static void assertNotAssigned(PrismObject user, String targetOid, QName refType, QName relation) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (QNameUtil.match(refType, targetRef.getType())) { if (targetOid.equals(targetRef.getOid()) && getPrismContext().relationMatches(targetRef.getRelation(), relation)) { - AssertJUnit.fail(user + " does have assigned "+refType.getLocalPart()+" "+targetOid+", relation "+relation+"while not expecting it"); + AssertJUnit.fail(user + " does have assigned " + refType.getLocalPart() + " " + targetOid + ", relation " + relation + "while not expecting it"); } } } @@ -121,20 +109,21 @@ public static void assertNotAssigned(PrismObject user, public static void assertAssignments(PrismObject user, int expectedNumber) { F userType = user.asObjectable(); - assertEquals("Unexepected number of assignments in "+user+": "+userType.getAssignment(), expectedNumber, userType.getAssignment().size()); + assertEquals("Unexpected number of assignments in " + user + ": " + userType.getAssignment(), expectedNumber, userType.getAssignment().size()); } public static void assertInducements(PrismObject role, int expectedNumber) { R roleType = role.asObjectable(); - assertEquals("Unexepected number of inducements in "+role+": "+roleType.getInducement(), + assertEquals("Unexpected number of inducements in " + role + ": " + roleType.getInducement(), expectedNumber, roleType.getInducement().size()); } - public static void assertAssignments(PrismObject user, Class expectedType, int expectedNumber) { + public static void assertAssignments( + PrismObject user, Class expectedType, int expectedNumber) { F userType = user.asObjectable(); int actualAssignments = 0; List assignments = userType.getAssignment(); - for (AssignmentType assignment: assignments) { + for (AssignmentType assignment : assignments) { ObjectReferenceType targetRef = assignment.getTargetRef(); if (targetRef != null) { QName type = targetRef.getType(); @@ -146,13 +135,14 @@ public static void assertAssignments(PrismObjec } } } - assertEquals("Unexepected number of assignments of type "+expectedType+" in "+user+": "+userType.getAssignment(), expectedNumber, actualAssignments); + assertEquals("Unexpected number of assignments of type " + expectedType + " in " + user + + ": " + userType.getAssignment(), expectedNumber, actualAssignments); } public static void assertNoAssignments(PrismObject user) { F userType = user.asObjectable(); List assignments = userType.getAssignment(); - assertTrue(user + " does have assignments "+assignments+" while not expecting it", assignments.isEmpty()); + assertTrue(user + " does have assignments " + assignments + " while not expecting it", assignments.isEmpty()); } public static AssignmentType assertAssignedRole(PrismObject user, String roleOid) { @@ -177,12 +167,12 @@ public static void assertAssignedOrgs(PrismObject user, public static void assertAssignedTargets(PrismObject user, String typeDesc, QName type, String... expectedTargetOids) { List haveTagetOids = getAssignedOids(user, type); - PrismAsserts.assertSets("Wrong "+typeDesc+" in "+user, haveTagetOids, expectedTargetOids); + PrismAsserts.assertSets("Wrong " + typeDesc + " in " + user, haveTagetOids, expectedTargetOids); } public static void assertAssignedTargets(PrismObject user, String typeDesc, QName type, Collection expectedTargetOids) { List haveTagetOids = getAssignedOids(user, type); - PrismAsserts.assertSets("Wrong "+typeDesc+" in "+user, haveTagetOids, expectedTargetOids); + PrismAsserts.assertSets("Wrong " + typeDesc + " in " + user, haveTagetOids, expectedTargetOids); } public static AssignmentType assertInducedRole(PrismObject user, String roleOid) { @@ -192,7 +182,7 @@ public static AssignmentType assertInducedRole(Pris private static List getAssignedOids(PrismObject user, QName type) { F userType = user.asObjectable(); List haveTagetOids = new ArrayList<>(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (type.equals(targetRef.getType())) { @@ -205,14 +195,14 @@ private static List getAssignedOids(PrismObject public static void assertNotAssignedResource(PrismObject user, String resourceOid) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { if (assignmentType.getConstruction() == null) { continue; } ObjectReferenceType targetRef = assignmentType.getConstruction().getResourceRef(); if (targetRef != null) { if (resourceOid.equals(targetRef.getOid())) { - AssertJUnit.fail(user + " does have assigned resource "+resourceOid+" while not expecting it"); + AssertJUnit.fail(user + " does have assigned resource " + resourceOid + " while not expecting it"); } } } @@ -220,7 +210,7 @@ public static void assertNotAssignedResource(PrismObject void assertAssignedResource(PrismObject user, String resourceOid) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { if (assignmentType.getConstruction() == null) { continue; } @@ -231,17 +221,17 @@ public static void assertAssignedResource(PrismObject u } } } - AssertJUnit.fail(user + " does NOT have assigned resource "+resourceOid+" while expecting it"); + AssertJUnit.fail(user + " does NOT have assigned resource " + resourceOid + " while expecting it"); } public static void assertNotAssignedOrg(PrismObject user, String orgOid, QName relation) { F userType = user.asObjectable(); - for (AssignmentType assignmentType: userType.getAssignment()) { + for (AssignmentType assignmentType : userType.getAssignment()) { ObjectReferenceType targetRef = assignmentType.getTargetRef(); if (targetRef != null) { if (OrgType.COMPLEX_TYPE.equals(targetRef.getType())) { if (orgOid.equals(targetRef.getOid()) && getPrismContext().relationMatches(relation, targetRef.getRelation())) { - AssertJUnit.fail(user + " does have assigned OrgType "+orgOid+" with relation "+relation+" while not expecting it"); + AssertJUnit.fail(user + " does have assigned OrgType " + orgOid + " with relation " + relation + " while not expecting it"); } } } @@ -261,7 +251,7 @@ public static void assertAssignedOrg(PrismObject focus, Str } public static void assertHasOrg(PrismObject object, String orgOid) { - for (ObjectReferenceType orgRef: object.asObjectable().getParentOrgRef()) { + for (ObjectReferenceType orgRef : object.asObjectable().getParentOrgRef()) { if (orgOid.equals(orgRef.getOid())) { return; } @@ -270,7 +260,7 @@ public static void assertHasOrg(PrismObject object, St } public static boolean hasOrg(PrismObject user, String orgOid, QName relation) { - for (ObjectReferenceType orgRef: user.asObjectable().getParentOrgRef()) { + for (ObjectReferenceType orgRef : user.asObjectable().getParentOrgRef()) { if (orgOid.equals(orgRef.getOid()) && getPrismContext().relationMatches(relation, orgRef.getRelation())) { return true; @@ -280,43 +270,42 @@ public static boolean hasOrg(PrismObject user, String } public static void assertHasOrg(PrismObject user, String orgOid, QName relation) { - AssertJUnit.assertTrue(user + " does not have org " + orgOid + ", relation "+relation, hasOrg(user, orgOid, relation)); + AssertJUnit.assertTrue(user + " does not have org " + orgOid + ", relation " + relation, hasOrg(user, orgOid, relation)); } public static void assertHasNoOrg(PrismObject user, String orgOid, QName relation) { - AssertJUnit.assertFalse(user + " has org " + orgOid + ", relation "+relation+ " even if should NOT have it", hasOrg(user, orgOid, relation)); + AssertJUnit.assertFalse(user + " has org " + orgOid + ", relation " + relation + " even if should NOT have it", hasOrg(user, orgOid, relation)); } public static void assertHasNoOrg(PrismObject user) { - assertTrue(user + " does have orgs "+user.asObjectable().getParentOrgRef()+" while not expecting them", user.asObjectable().getParentOrgRef().isEmpty()); + assertTrue(user + " does have orgs " + user.asObjectable().getParentOrgRef() + " while not expecting them", user.asObjectable().getParentOrgRef().isEmpty()); } public static void assertHasOrgs(PrismObject user, int expectedNumber) { O userType = user.asObjectable(); - assertEquals("Unexpected number of orgs in "+user+": "+userType.getParentOrgRef(), expectedNumber, userType.getParentOrgRef().size()); + assertEquals("Unexpected number of orgs in " + user + ": " + userType.getParentOrgRef(), expectedNumber, userType.getParentOrgRef().size()); } public static void assertHasArchetypes(PrismObject object, int expectedNumber) { O objectable = object.asObjectable(); - assertEquals("Unexpected number of archetypes in "+object+": "+objectable.getArchetypeRef(), expectedNumber, objectable.getArchetypeRef().size()); + assertEquals("Unexpected number of archetypes in " + object + ": " + objectable.getArchetypeRef(), expectedNumber, objectable.getArchetypeRef().size()); } public static void assertHasArchetype(PrismObject object, String oid) { AssertJUnit.assertTrue(object + " does not have archetype " + oid, ObjectTypeUtil.hasArchetype(object, oid)); } - public static void assertVersionIncrease(PrismObject objectOld, PrismObject objectNew) { - Long versionOld = parseVersion(objectOld); - Long versionNew = parseVersion(objectNew); - assertTrue("Version not increased (from "+versionOld+" to "+versionNew+")", versionOld < versionNew); + public static void assertVersionIncrease( + PrismObject objectOld, PrismObject objectNew) { + long versionOld = parseVersion(objectOld); + long versionNew = parseVersion(objectNew); + assertTrue("Version not increased (from " + versionOld + " to " + versionNew + ")", + versionOld < versionNew); } - public static Long parseVersion(PrismObject object) { + public static long parseVersion(PrismObject object) { String version = object.getVersion(); - if (version == null) { - return null; - } - return Long.valueOf(version); + return Long.parseLong(version); } public static void assertVersion(PrismObject object, int expectedVersion) { @@ -324,42 +313,43 @@ public static void assertVersion(PrismObject object, i } public static void assertVersion(PrismObject object, String expectedVersion) { - assertEquals("Wrong version for "+object, expectedVersion, object.getVersion()); + assertEquals("Wrong version for " + object, expectedVersion, object.getVersion()); } public static void assertOid(PrismObject object, String expectedOid) { - assertEquals("Wrong OID for "+object, expectedOid, object.getOid()); + assertEquals("Wrong OID for " + object, expectedOid, object.getOid()); } + @UnusedTestElement public static void assertContainsCaseIgnore(String message, Collection actualValues, String expectedValue) { - AssertJUnit.assertNotNull(message+", expected "+expectedValue+", got null", actualValues); - for (String actualValue: actualValues) { + AssertJUnit.assertNotNull(message + ", expected " + expectedValue + ", got null", actualValues); + for (String actualValue : actualValues) { if (StringUtils.equalsIgnoreCase(actualValue, expectedValue)) { return; } } - AssertJUnit.fail(message+", expected "+expectedValue+", got "+actualValues); + AssertJUnit.fail(message + ", expected " + expectedValue + ", got " + actualValues); } public static void assertNotContainsCaseIgnore(String message, Collection actualValues, String expectedValue) { if (actualValues == null) { return; } - for (String actualValue: actualValues) { + for (String actualValue : actualValues) { if (StringUtils.equalsIgnoreCase(actualValue, expectedValue)) { - AssertJUnit.fail(message+", expected that value "+expectedValue+" will not be present but it is"); + AssertJUnit.fail(message + ", expected that value " + expectedValue + " will not be present but it is"); } } } public static void assertObjectClass(ShadowType shadow, QName expectedStructuralObjectClass, QName... expectedAuxiliaryObjectClasses) { - assertEquals("Wrong object class in "+shadow, expectedStructuralObjectClass, shadow.getObjectClass()); - PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary object classes in "+shadow, shadow.getAuxiliaryObjectClass(), expectedAuxiliaryObjectClasses); + assertEquals("Wrong object class in " + shadow, expectedStructuralObjectClass, shadow.getObjectClass()); + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary object classes in " + shadow, shadow.getAuxiliaryObjectClass(), expectedAuxiliaryObjectClasses); } public static void assertInstanceOf(String message, Object object, Class expectedClass) { - assertNotNull(message+" is null", object); - assertTrue(message+" is not instance of "+expectedClass+", it is "+object.getClass(), + assertNotNull(message + " is null", object); + assertTrue(message + " is not instance of " + expectedClass + ", it is " + object.getClass(), expectedClass.isAssignableFrom(object.getClass())); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java index 3bc9ae14c10..1fb500469fa 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java @@ -363,21 +363,6 @@ public static void debugDumpWithLabelShortDumpLn(StringBuilder sb, String label, sb.append("\n"); } - public static String debugDumpXsdAnyProperties(Collection xsdAnyCollection, int indent) { - StringBuilder sb = new StringBuilder(); - indentDebugDump(sb, indent); - sb.append(getCollectionOpeningSymbol(xsdAnyCollection)); - for (Object element : xsdAnyCollection) { - sb.append("\n"); - indentDebugDump(sb, indent+1); - sb.append(PrettyPrinter.prettyPrintElementAsProperty(element)); - } - sb.append("\n"); - indentDebugDump(sb, indent); - sb.append(getCollectionClosingSymbol(xsdAnyCollection)); - return sb.toString(); - } - public static String getCollectionOpeningSymbol(Collection col) { if (col instanceof List) { return "["; diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/AbstractModelCommonTest.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/AbstractModelCommonTest.java index a7a13e48e83..5f767a8dc87 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/AbstractModelCommonTest.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/AbstractModelCommonTest.java @@ -8,14 +8,18 @@ import java.io.File; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.test.NullTaskImpl; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; +import com.evolveum.midpoint.util.DebugDumpable; /** * @author semancik */ -public class AbstractModelCommonTest extends AbstractUnitTest { +public class AbstractModelCommonTest extends AbstractUnitTest + implements OperationResultTestMixin { protected static final File COMMON_DIR = new File("src/test/resources/common"); @@ -25,4 +29,12 @@ public class AbstractModelCommonTest extends AbstractUnitTest { protected Task createTask() { return new NullTaskImpl(); } + + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpression.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpression.java index 1cf8bba5cdb..c01530effb7 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpression.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpression.java @@ -81,7 +81,7 @@ public class TestExpression extends AbstractModelCommonTest { protected static final String INPUT_VALUE = "garbage in"; protected static final String GROOVY_SCRIPT_OUTPUT_SUCCESS = "SUCCESS"; - private static final Trace LOGGER = TraceManager.getTrace(TestExpression.class); + private static final Trace logger = TraceManager.getTrace(TestExpression.class); protected PrismContext prismContext; protected ExpressionFactory expressionFactory; @@ -107,23 +107,26 @@ public void setup() throws SchemaException, SAXException, IOException { expressionProfile = compileExpressionProfile(getExpressionProfileName()); System.out.println("Using expression profile: " + expressionProfile); - LOGGER.info("EXPRESSION PROFILE: {}", expressionProfile); + logger.info("EXPRESSION PROFILE: {}", expressionProfile); } @Test public void test100AsIs() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); ExpressionType expressionType = parseExpression(EXPRESSION_ASIS_FILE); Collection> sources = prepareStringSources(); ExpressionVariables variables = prepareBasicVariables(); - ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContext(sources, variables, getTestNameShort(), null); + ExpressionEvaluationContext expressionContext = + new ExpressionEvaluationContext(sources, variables, getTestNameShort(), null); // WHEN - PrismValueDeltaSetTriple> outputTriple = evaluatePropertyExpression(expressionType, PrimitiveType.STRING, expressionContext, result); + PrismValueDeltaSetTriple> outputTriple = + evaluatePropertyExpression( + expressionType, PrimitiveType.STRING, expressionContext, result); // THEN assertOutputTriple(outputTriple) @@ -138,7 +141,7 @@ public void test100AsIs() throws Exception { @Test public void test110Path() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -164,7 +167,7 @@ public void test110Path() throws Exception { @Test public void test120Value() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -190,7 +193,7 @@ public void test120Value() throws Exception { @Test public void test130Const() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -216,7 +219,7 @@ public void test130Const() throws Exception { @Test public void test150ScriptGroovySimple() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -242,7 +245,7 @@ public void test150ScriptGroovySimple() throws Exception { @Test public void test152ScriptGroovySystemAllow() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -268,7 +271,7 @@ public void test152ScriptGroovySystemAllow() throws Exception { @Test public void test154ScriptGroovySystemDeny() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -294,7 +297,7 @@ public void test154ScriptGroovySystemDeny() throws Exception { @Test public void test160ScriptJavaScript() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -320,7 +323,7 @@ public void test160ScriptJavaScript() throws Exception { @Test public void test200IterationCondition() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -392,7 +395,7 @@ protected PrismValueDeltaSetTri throws SchemaException, ObjectNotFoundException, SecurityViolationException, ExpressionEvaluationException, CommunicationException, ConfigurationException { Expression expression = expressionFactory.makeExpression(expressionType, outputDefinition, getExpressionProfile(), expressionContext.getContextDescription(), expressionContext.getTask(), result); - LOGGER.debug("Starting evaluation of expression: {}", expression); + logger.debug("Starting evaluation of expression: {}", expression); return expression.evaluate(expressionContext, result); } @@ -424,12 +427,12 @@ protected void evaluateExpressi } catch (SecurityViolationException e) { // Exception may happen here, or it may happen later. // Expected - LOGGER.debug("Expected exception", e); + logger.debug("Expected exception", e); assertTrue("Wrong exception message: " + e.getMessage(), e.getMessage().contains("Access to script language")); return; } - LOGGER.debug("Starting evaluation of expression (expecting security violation): {}", expression); + logger.debug("Starting evaluation of expression (expecting security violation): {}", expression); try { expression.evaluate(expressionContext, result); @@ -438,7 +441,7 @@ protected void evaluateExpressi } catch (SecurityViolationException e) { // Expected - LOGGER.debug("Expected exception", e); + logger.debug("Expected exception", e); assertTrue("Wrong exception message: " + e.getMessage(), e.getMessage().contains("Access to expression evaluator") || e.getMessage().contains("Access to Groovy method")); @@ -454,7 +457,7 @@ protected void evaluatePropertyExpressionRestricted(ExpressionType expressio evaluateExpressionRestricted(expressionType, outputDefinition, expressionContext, result); } - protected void evaluatePropertyExpressionRestricted( + protected void evaluatePropertyExpressionRestricted( ExpressionType expressionType, PrimitiveType outputType, ExpressionEvaluationContext expressionContext, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, @@ -469,7 +472,8 @@ protected void rememberScriptExecutionCount() { protected void assertScriptExecutionIncrement(int expectedIncrement) { long currentScriptExecutionCount = InternalMonitor.getCount(InternalCounters.SCRIPT_EXECUTION_COUNT); long actualIncrement = currentScriptExecutionCount - lastScriptExecutionCount; - assertEquals("Unexpected increment in script execution count", (long) expectedIncrement, actualIncrement); + assertEquals("Unexpected increment in script execution count", + expectedIncrement, actualIncrement); lastScriptExecutionCount = currentScriptExecutionCount; } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionProfileSafe.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionProfileSafe.java index faa8c7ed01f..c3fb18a8cd1 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionProfileSafe.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionProfileSafe.java @@ -31,7 +31,7 @@ protected String getExpressionProfileName() { @Override public void test130Const() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -52,7 +52,7 @@ public void test130Const() throws Exception { @Override public void test154ScriptGroovySystemDeny() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); @@ -73,7 +73,7 @@ public void test154ScriptGroovySystemDeny() throws Exception { @Override public void test160ScriptJavaScript() throws Exception { // GIVEN - OperationResult result = new OperationResult(contextName()); + OperationResult result = createOperationResult(); rememberScriptExecutionCount(); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java index 36b89d383f5..c8689207af0 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java @@ -167,7 +167,8 @@ public void testResolvePathPolyStringOdoNorm() throws Exception { } - private T resolvePath(String path, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + private T resolvePath(String path, final String TEST_NAME) + throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ExpressionVariables variables = createVariables(); return resolvePath(path, variables, TEST_NAME); } @@ -178,7 +179,7 @@ private T resolvePathOdo(String path, final String TEST_NAME) throws SchemaE } private T resolvePath(String path, ExpressionVariables variables, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - OperationResult result = new OperationResult(TestExpressionUtil.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ItemPath itemPath = toItemPath(path); // WHEN diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java index 691e9b72752..2ad901ef89e 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java @@ -14,27 +14,25 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; - -import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; -import com.evolveum.midpoint.common.Clock; -import com.evolveum.midpoint.common.LocalizationService; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.crypto.KeyStoreBasedProtectorBuilder; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.xml.sax.SAXException; +import com.evolveum.midpoint.common.Clock; +import com.evolveum.midpoint.common.LocalizationService; +import com.evolveum.midpoint.common.LocalizationTestUtil; import com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary; import com.evolveum.midpoint.model.common.expression.functions.FunctionLibraryUtil; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.crypto.KeyStoreBasedProtectorBuilder; import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.common.DirectoryFileObjectResolver; import com.evolveum.midpoint.repo.common.ObjectResolver; -import com.evolveum.midpoint.repo.common.expression.ExpressionSyntaxException; import com.evolveum.midpoint.repo.common.expression.ExpressionVariables; import com.evolveum.midpoint.schema.AccessDecision; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; @@ -45,26 +43,23 @@ import com.evolveum.midpoint.schema.expression.ScriptExpressionProfile; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.test.util.ParallelTestThread; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import com.evolveum.midpoint.common.LocalizationTestUtil; /** * @author Radovan Semancik */ -public abstract class AbstractScriptTest { +public abstract class AbstractScriptTest extends AbstractUnitTest + implements OperationResultTestMixin { protected static final QName PROPERTY_NAME = new QName(MidPointConstants.NS_MIDPOINT_TEST_PREFIX, "whatever"); protected static final File BASE_TEST_DIR = new File("src/test/resources/expression"); @@ -73,7 +68,6 @@ public abstract class AbstractScriptTest { public static final String VAR_POISON = "poison"; protected static final String RESULT_POISON_OK = "ALIVE"; - protected static final String POISON_DRINK_ERROR_MESSAGE = "ALIVE"; protected static final String RESULT_STRING_EXEC = "Hello world"; @@ -104,7 +98,7 @@ public void setupFactory() { localizationService = LocalizationTestUtil.getLocalizationService(); evaluator = createEvaluator(prismContext, protector); String languageUrl = evaluator.getLanguageUrl(); - System.out.println("Expression test for "+evaluator.getLanguageName()+": registering "+evaluator+" with URL "+languageUrl); + System.out.println("Expression test for " + evaluator.getLanguageName() + ": registering " + evaluator + " with URL " + languageUrl); scriptExpressionfactory.registerEvaluator(languageUrl, evaluator); } @@ -118,14 +112,13 @@ protected boolean supportsRootNode() { @Test public void testExpressionSimple() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-simple.xml", + evaluateAndAssertStringScalarExpression("expression-simple.xml", "testExpressionSimple", null, "foobar"); } - @Test public void testExpressionStringVariables() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-string-variables.xml", "testExpressionStringVariables", createVariables( @@ -141,19 +134,17 @@ public void testExpressionStringVariables() throws Exception { */ @Test public void testExpressionStringVariablesParallel() throws Exception { - final String TEST_NAME = "testExpressionStringVariablesParallel"; - // WHEN ParallelTestThread[] threads = TestUtil.multithread( (threadIndex) -> { - String foo = "FOO"+threadIndex; - String bar = "BAR"+threadIndex; + String foo = "FOO" + threadIndex; + String bar = "BAR" + threadIndex; - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-string-variables.xml", - "testExpressionStringVariablesParallel-"+threadIndex, + "testExpressionStringVariablesParallel-" + threadIndex, createVariables( "foo", foo, PrimitiveType.STRING, "bar", bar, PrimitiveType.STRING @@ -167,33 +158,32 @@ public void testExpressionStringVariablesParallel() throws Exception { } - @Test public void testExpressionObjectRefVariables() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-objectref-variables.xml", "testExpressionObjectRefVariables", createVariables( "foo", "Captain", String.class, "jack", - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) ), "Captain emp1234"); } @Test public void testExpressionObjectRefVariablesPolyString() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-objectref-variables-polystring.xml", "testExpressionObjectRefVariablesPolyString", createVariables( "foo", "Captain", PrimitiveType.STRING, "jack", - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) ), "Captain Jack Sparrow"); } @@ -202,7 +192,7 @@ public void testExpressionObjectRefVariablesPolyString() throws Exception { @Test public void testUserGivenName() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-user-given-name.xml", "testUserGivenName", createUserScriptVariables(), @@ -211,7 +201,7 @@ public void testUserGivenName() throws Exception { @Test public void testUserExtensionShip() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-user-extension-ship.xml", "testUserExtensionShip", createUserScriptVariables(), @@ -220,7 +210,7 @@ public void testUserExtensionShip() throws Exception { @Test public void testUserExtensionShipPath() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-user-extension-ship-path.xml", "testUserExtensionShipPath", createUserScriptVariables(), @@ -229,7 +219,7 @@ public void testUserExtensionShipPath() throws Exception { @Test public void testUserExtensionStringifyFullName() throws Exception { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-user-stringify-full-name.xml", "testUserExtensionStringifyFullName", createUserScriptVariables(), @@ -244,13 +234,13 @@ public void testUserExtensionStringifyFullName() throws Exception { private ExpressionVariables createUserScriptVariables() { return createVariables( ExpressionConstants.VAR_USER, - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - // We want 'user' variable to contain user object, not the reference. We want the reference resolved. - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class), + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + // We want 'user' variable to contain user object, not the reference. We want the reference resolved. + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class), ExpressionConstants.VAR_FOCUS, - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - // We want 'user' variable to contain user object, not the reference. We want the reference resolved. - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class)); + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + // We want 'user' variable to contain user object, not the reference. We want the reference resolved. + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class)); } // TODO: shadow + attributes @@ -261,39 +251,39 @@ public void testRootNode() throws Exception { return; } - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-root-node.xml", "testRootNode", createVariables( null, // root node - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class)), + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class)), "Black Pearl"); } @Test public void testExpressionList() throws Exception { - evaluateAndAssertStringListExpresssion( + evaluateAndAssertStringListExpression( "expression-list.xml", "testExpressionList", createVariables( "jack", - MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), - // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. - prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) + MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE), + // We want 'jack' variable to contain user object, not the reference. We want the reference resolved. + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class) ), "Leaders", "Followers"); } @Test public void testExpressionFunc() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-func.xml", + evaluateAndAssertStringScalarExpression("expression-func.xml", "testExpressionFunc", null, "gulocka v jamocke"); } @Test public void testExpressionFuncConcatName() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-func-concatname.xml", + evaluateAndAssertStringScalarExpression("expression-func-concatname.xml", "testExpressionFuncConcatName", null, "Horatio Torquemada Marley"); } @@ -302,23 +292,30 @@ private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws Sc new File(getTestDir(), fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE); } - private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, ItemDefinition outputDefinition, - ExpressionVariables variables, String shortDesc, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - ScriptExpression scriptExpression = createScriptExpression(scriptType, outputDefinition, shortDesc); - List> resultValues = scriptExpression.evaluate(variables, null, false, shortDesc, null, result); + private List> evaluateExpression( + ScriptExpressionEvaluatorType scriptType, ItemDefinition outputDefinition, + ExpressionVariables variables, String shortDesc, OperationResult result) + throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, + CommunicationException, ConfigurationException, SecurityViolationException { + ScriptExpression scriptExpression = createScriptExpression(scriptType, outputDefinition); + @SuppressWarnings("deprecation") + List> resultValues = + scriptExpression.evaluate(variables, null, false, shortDesc, null, result); if (resultValues != null) { - for (PrismPropertyValue resultVal: resultValues) { + for (PrismPropertyValue resultVal : resultValues) { if (resultVal.getParent() != null) { - AssertJUnit.fail("Result value "+resultVal+" from expression "+scriptExpression+" has parent"); + AssertJUnit.fail("Result value " + resultVal + " from expression " + scriptExpression + " has parent"); } } } return resultValues; } - private ScriptExpression createScriptExpression(ScriptExpressionEvaluatorType expressionType, ItemDefinition outputDefinition, String shortDesc) throws ExpressionSyntaxException { + private ScriptExpression createScriptExpression( + ScriptExpressionEvaluatorType expressionType, ItemDefinition outputDefinition) { String language = expressionType.getLanguage(); - ScriptExpression expression = new ScriptExpression(scriptExpressionfactory.getEvaluators().get(language), expressionType); + ScriptExpression expression = new ScriptExpression( + scriptExpressionfactory.getEvaluators().get(language), expressionType); expression.setOutputDefinition(outputDefinition); expression.setObjectResolver(scriptExpressionfactory.getObjectResolver()); expression.setFunctions(new ArrayList<>(scriptExpressionfactory.getFunctions())); @@ -345,24 +342,23 @@ protected ScriptExpressionProfile getScriptExpressionProfile(String language) { return null; } - private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, QName typeName, boolean scalar, - ExpressionVariables variables, String shortDesc, OperationResult opResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - MutableItemDefinition outputDefinition = PrismTestUtil.getPrismContext().definitionFactory().createPropertyDefinition(PROPERTY_NAME, typeName); + private List> evaluateExpression( + ScriptExpressionEvaluatorType scriptType, QName typeName, boolean scalar, + ExpressionVariables variables, String shortDesc, OperationResult opResult) + throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, + CommunicationException, ConfigurationException, SecurityViolationException { + MutableItemDefinition outputDefinition = PrismTestUtil.getPrismContext() + .definitionFactory().createPropertyDefinition(PROPERTY_NAME, typeName); if (!scalar) { outputDefinition.setMaxOccurs(-1); } return evaluateExpression(scriptType, outputDefinition, variables, shortDesc, opResult); } - private PrismPropertyValue evaluateExpressionScalar(ScriptExpressionEvaluatorType scriptType, QName typeName, - ExpressionVariables variables, String shortDesc, OperationResult opResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - List> expressionResultList = evaluateExpression(scriptType, typeName, true, variables, shortDesc, opResult); - return asScalar(expressionResultList, shortDesc); - } - - private PrismPropertyValue asScalar(List> expressionResultList, String shortDesc) { + private PrismPropertyValue asScalar( + List> expressionResultList, String shortDesc) { if (expressionResultList.size() > 1) { - AssertJUnit.fail("Expression "+shortDesc+" produces a list of "+expressionResultList.size()+" while only expected a single value: "+expressionResultList); + AssertJUnit.fail("Expression " + shortDesc + " produces a list of " + expressionResultList.size() + " while only expected a single value: " + expressionResultList); } if (expressionResultList.isEmpty()) { return null; @@ -370,44 +366,65 @@ private PrismPropertyValue asScalar(List> expressio return expressionResultList.iterator().next(); } - protected void evaluateAndAssertStringScalarExpresssion(String fileName, String testName, ExpressionVariables variables, String expectedValue) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { - List> expressionResultList = evaluateStringExpresssion(fileName, testName, variables, true); + protected void evaluateAndAssertStringScalarExpression( + String fileName, String testName, ExpressionVariables variables, String expectedValue) + throws ObjectNotFoundException, CommunicationException, SecurityViolationException, + SchemaException, IOException, ExpressionEvaluationException, ConfigurationException { + List> expressionResultList = evaluateStringExpression(fileName, testName, variables); PrismPropertyValue expressionResult = asScalar(expressionResultList, testName); - assertNotNull("Expression "+testName+" resulted in null value (expected '"+expectedValue+"')", expressionResult); - assertEquals("Expression "+testName+" resulted in wrong value", expectedValue, expressionResult.getValue()); + assertNotNull("Expression " + testName + " resulted in null value (expected '" + expectedValue + "')", expressionResult); + assertEquals("Expression " + testName + " resulted in wrong value", expectedValue, expressionResult.getValue()); } - protected void evaluateAndAssertStringScalarExpresssionRestricted(String fileName, String testName, ExpressionVariables variables) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + protected void evaluateAndAssertStringScalarExpressionRestricted( + String fileName, String testName, ExpressionVariables variables) + throws ObjectNotFoundException, CommunicationException, SchemaException, IOException, + ExpressionEvaluationException, ConfigurationException { try { - List> expressionResultList = evaluateStringExpresssion(fileName, testName, variables, true); - AssertJUnit.fail("Expression "+testName+": unexpected success, result value: "+ expressionResultList); + List> expressionResultList = evaluateStringExpression(fileName, testName, variables); + AssertJUnit.fail("Expression " + testName + ": unexpected success, result value: " + expressionResultList); } catch (SecurityViolationException e) { System.out.println("Expected exception: " + e); LOGGER.debug("Expected exception", e); } } - private void evaluateAndAssertStringListExpresssion(String fileName, String testName, ExpressionVariables variables, String... expectedValues) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { - List> expressionResultList = evaluateStringExpresssion(fileName, testName, variables, true); - TestUtil.assertSetEquals("Expression "+testName+" resulted in wrong values", PrismValueCollectionsUtil.getValues(expressionResultList), expectedValues); + private void evaluateAndAssertStringListExpression(String fileName, String testName, + ExpressionVariables variables, String... expectedValues) + throws ObjectNotFoundException, CommunicationException, SecurityViolationException, + SchemaException, IOException, ExpressionEvaluationException, ConfigurationException { + List> expressionResultList = + evaluateStringExpression(fileName, testName, variables); + TestUtil.assertSetEquals("Expression " + testName + " resulted in wrong values", + PrismValueCollectionsUtil.getValues(expressionResultList), expectedValues); } - protected void evaluateAndAssertBooleanScalarExpresssion(String fileName, String testName, ExpressionVariables variables, Boolean expectedValue) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { - List> expressionResultList = evaluateBooleanExpresssion(fileName, testName, variables, true); + + protected void evaluateAndAssertBooleanScalarExpression(String fileName, + String testName, ExpressionVariables variables, Boolean expectedValue) + throws ObjectNotFoundException, CommunicationException, SecurityViolationException, + SchemaException, IOException, ExpressionEvaluationException, ConfigurationException { + List> expressionResultList = evaluateBooleanExpression(fileName, testName, variables); PrismPropertyValue expressionResult = asScalar(expressionResultList, testName); - assertNotNull("Expression "+testName+" resulted in null value (expected '"+expectedValue+"')", expressionResult); - assertEquals("Expression "+testName+" resulted in wrong value", expectedValue, expressionResult.getValue()); + assertNotNull("Expression " + testName + " resulted in null value (expected '" + expectedValue + "')", expressionResult); + assertEquals("Expression " + testName + " resulted in wrong value", expectedValue, expressionResult.getValue()); } - private List> evaluateStringExpresssion(String fileName, String testName, ExpressionVariables variables, boolean scalar) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + private List> evaluateStringExpression( + String fileName, String testName, ExpressionVariables variables) + throws ObjectNotFoundException, CommunicationException, SecurityViolationException, + SchemaException, IOException, ExpressionEvaluationException, ConfigurationException { ScriptExpressionEvaluatorType scriptType = parseScriptType(fileName); - OperationResult opResult = new OperationResult(testName); + OperationResult opResult = createOperationResult(); return evaluateExpression(scriptType, DOMUtil.XSD_STRING, true, variables, testName, opResult); } - private List> evaluateBooleanExpresssion(String fileName, String testName, ExpressionVariables variables, boolean scalar) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + private List> evaluateBooleanExpression( + String fileName, String testName, ExpressionVariables variables) + throws ObjectNotFoundException, CommunicationException, SecurityViolationException, + SchemaException, IOException, ExpressionEvaluationException, ConfigurationException { ScriptExpressionEvaluatorType scriptType = parseScriptType(fileName); - OperationResult opResult = new OperationResult(testName); + OperationResult opResult = createOperationResult(); return evaluateExpression(scriptType, DOMUtil.XSD_BOOLEAN, true, variables, testName, opResult); } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java index d2d08061a37..6945dc9d755 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java @@ -48,7 +48,7 @@ protected File getTestDir() { @Test public void testExpressionPolyStringEquals101() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals101", createVariables( @@ -60,7 +60,7 @@ public void testExpressionPolyStringEquals101() throws Exception { @Test public void testExpressionPolyStringEquals102() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals102", createVariables( @@ -72,7 +72,7 @@ public void testExpressionPolyStringEquals102() throws Exception { @Test public void testExpressionPolyStringEquals111() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals111", createVariables( @@ -85,7 +85,7 @@ public void testExpressionPolyStringEquals111() throws Exception { @Test public void testExpressionPolyStringEquals112() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals112", createVariables( @@ -97,7 +97,7 @@ public void testExpressionPolyStringEquals112() throws Exception { @Test public void testExpressionPolyStringEquals121() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals121", createVariables( @@ -109,7 +109,7 @@ public void testExpressionPolyStringEquals121() throws Exception { @Test public void testExpressionPolyStringEquals122() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals122", createVariables( @@ -121,7 +121,7 @@ public void testExpressionPolyStringEquals122() throws Exception { @Test public void testExpressionPolyStringEquals201() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals201", createVariables( @@ -133,7 +133,7 @@ public void testExpressionPolyStringEquals201() throws Exception { @Test public void testExpressionPolyStringEquals202() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals202", createVariables( @@ -145,7 +145,7 @@ public void testExpressionPolyStringEquals202() throws Exception { @Test public void testExpressionPolyStringEquals211() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals211", createVariables( @@ -157,7 +157,7 @@ public void testExpressionPolyStringEquals211() throws Exception { @Test public void testExpressionPolyStringEquals212() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals212", createVariables( @@ -169,7 +169,7 @@ public void testExpressionPolyStringEquals212() throws Exception { @Test public void testExpressionPolyStringEquals221() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals221", createVariables( @@ -181,7 +181,7 @@ public void testExpressionPolyStringEquals221() throws Exception { @Test public void testExpressionPolyStringEquals222() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals222", createVariables( @@ -193,7 +193,7 @@ public void testExpressionPolyStringEquals222() throws Exception { @Test public void testExpressionPolyStringEqualsStringify101() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify101", createVariables( @@ -205,7 +205,7 @@ public void testExpressionPolyStringEqualsStringify101() throws Exception { @Test public void testExpressionPolyStringEqualsStringify102() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify102", createVariables( @@ -217,7 +217,7 @@ public void testExpressionPolyStringEqualsStringify102() throws Exception { @Test public void testExpressionPolyStringEqualsStringify111() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify111", createVariables( @@ -229,7 +229,7 @@ public void testExpressionPolyStringEqualsStringify111() throws Exception { @Test public void testExpressionPolyStringEqualsStringify112() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify112", createVariables( @@ -241,7 +241,7 @@ public void testExpressionPolyStringEqualsStringify112() throws Exception { @Test public void testExpressionPolyStringEqualsStringify121() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify121", createVariables( @@ -253,7 +253,7 @@ public void testExpressionPolyStringEqualsStringify121() throws Exception { @Test public void testExpressionPolyStringEqualsStringify122() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify122", createVariables( @@ -265,7 +265,7 @@ public void testExpressionPolyStringEqualsStringify122() throws Exception { @Test public void testExpressionPolyStringEqualsStringify201() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify201", createVariables( @@ -277,7 +277,7 @@ public void testExpressionPolyStringEqualsStringify201() throws Exception { @Test public void testExpressionPolyStringEqualsStringify202() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify202", createVariables( @@ -289,7 +289,7 @@ public void testExpressionPolyStringEqualsStringify202() throws Exception { @Test public void testExpressionPolyStringEqualsStringify211() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify211", createVariables( @@ -301,7 +301,7 @@ public void testExpressionPolyStringEqualsStringify211() throws Exception { @Test public void testExpressionPolyStringEqualsStringify212() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify212", createVariables( @@ -313,7 +313,7 @@ public void testExpressionPolyStringEqualsStringify212() throws Exception { @Test public void testExpressionPolyStringEqualsStringify221() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify221", createVariables( @@ -325,7 +325,7 @@ public void testExpressionPolyStringEqualsStringify221() throws Exception { @Test public void testExpressionPolyStringEqualsStringify222() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify222", createVariables( @@ -340,7 +340,7 @@ public void testLookAtPoison() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-look.xml", "testLookAtPoison", createPoisonVariables(poison), @@ -358,7 +358,7 @@ public void testSmellPoison() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell.xml", "testSmellPoison", createPoisonVariables(poison), @@ -376,7 +376,7 @@ public void testSmellPoisonTricky() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell-tricky.xml", "testSmellPoisonTricky", createPoisonVariables(poison), @@ -395,7 +395,7 @@ public void testSmellPoisonDynamic() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell-dynamic.xml", "testSmellPoisonDynamic", createPoisonVariables(poison), @@ -414,7 +414,7 @@ public void testSmellPoisonVeryDynamic() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell-very-dynamic.xml", "testSmellPoisonVeryDynamic", createPoisonVariables(poison), @@ -433,7 +433,7 @@ public void testSmellPoisonReflection() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell-reflection.xml", "testSmellPoisonReflection", createPoisonVariables(poison), @@ -454,7 +454,7 @@ public void testDrinkPoison() throws Exception { // WHEN try { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-drink.xml", "testDrinkPoison", createPoisonVariables(poison), @@ -486,7 +486,7 @@ public void testSyntaxError() throws Exception { // WHEN try { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-syntax-error.xml", "testSyntaxError", createPoisonVariables(poison), @@ -509,7 +509,7 @@ public void testStringExec() throws Exception { } // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-string-exec.xml", "testStringExec", null, @@ -529,7 +529,7 @@ public void testListExec() throws Exception { } // WHEN - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-list-exec.xml", "testListExec", null, diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressionsSandbox.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressionsSandbox.java index 5943298aebd..823d949e1ff 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressionsSandbox.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressionsSandbox.java @@ -14,7 +14,6 @@ import com.evolveum.midpoint.schema.AccessDecision; import com.evolveum.midpoint.schema.expression.ExpressionPermissionProfile; -import com.evolveum.midpoint.schema.expression.ExpressionProfile; import com.evolveum.midpoint.schema.expression.ScriptExpressionProfile; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; @@ -58,7 +57,7 @@ public void testSmellPoison() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-poison-smell.xml", "testSmellPoison", createPoisonVariables(poison)); @@ -77,7 +76,7 @@ public void testSmellPoisonTricky() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-poison-smell-tricky.xml", "testDrinkPoisonTricky", createPoisonVariables(poison)); @@ -94,7 +93,7 @@ public void testSmellPoisonDynamic() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-poison-smell-dynamic.xml", "testSmellPoisonDynamic", createPoisonVariables(poison)); @@ -115,7 +114,7 @@ public void testSmellPoisonVeryDynamic() throws Exception { // WHEN try { - evaluateAndAssertStringScalarExpresssion( + evaluateAndAssertStringScalarExpression( "expression-poison-smell-very-dynamic.xml", "testSmellPoisonVeryDynamic", createPoisonVariables(poison), @@ -138,7 +137,7 @@ public void testSmellPoisonReflection() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-poison-smell-reflection.xml", "testSmellPoisonDynamic", createPoisonVariables(poison)); @@ -156,7 +155,7 @@ public void testDrinkPoison() throws Exception { Poison poison = new Poison(); // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-poison-drink.xml", "testDrinkPoison", createPoisonVariables(poison)); @@ -171,7 +170,7 @@ public void testDrinkPoison() throws Exception { public void testStringExec() throws Exception { // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-string-exec.xml", "testStringExec", null); @@ -188,7 +187,7 @@ public void testStringExec() throws Exception { public void testListExec() throws Exception { // WHEN - evaluateAndAssertStringScalarExpresssionRestricted( + evaluateAndAssertStringScalarExpressionRestricted( "expression-list-exec.xml", "testListExec", null); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java index cbe540afa1a..e33d244f03c 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java @@ -6,27 +6,26 @@ */ package com.evolveum.midpoint.model.common.expression.script; -import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; +import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; + import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.common.Clock; -import com.evolveum.midpoint.common.LocalizationTestUtil; -import com.evolveum.midpoint.prism.crypto.KeyStoreBasedProtectorBuilder; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.xml.sax.SAXException; +import com.evolveum.midpoint.common.Clock; +import com.evolveum.midpoint.common.LocalizationTestUtil; import com.evolveum.midpoint.model.common.expression.functions.FunctionLibrary; import com.evolveum.midpoint.model.common.expression.functions.FunctionLibraryUtil; import com.evolveum.midpoint.model.common.expression.script.jsr223.Jsr223ScriptEvaluator; @@ -34,6 +33,7 @@ import com.evolveum.midpoint.prism.PrimitiveType; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismPropertyValue; +import com.evolveum.midpoint.prism.crypto.KeyStoreBasedProtectorBuilder; import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.common.DirectoryFileObjectResolver; @@ -44,29 +44,26 @@ import com.evolveum.midpoint.schema.internals.InternalCounters; import com.evolveum.midpoint.schema.internals.InternalMonitor; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType; /** * @author semancik */ -public class TestScriptCaching extends AbstractUnitTest { +public class TestScriptCaching extends AbstractUnitTest + implements OperationResultTestMixin { private static final File TEST_DIR = new File("src/test/resources/expression/groovy"); protected static final File OBJECTS_DIR = new File("src/test/resources/objects"); private static final QName PROPERTY_NAME = new QName(MidPointConstants.NS_MIDPOINT_TEST_PREFIX, "whatever"); - protected ScriptExpressionFactory scriptExpressionfactory; - protected ScriptEvaluator evaluator; + protected ScriptExpressionFactory scriptExpressionfactory; + protected ScriptEvaluator evaluator; @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { @@ -96,43 +93,45 @@ public void testGetExtensionPropertyValue() throws Exception { // GIVEN InternalMonitor.reset(); - assertScriptMonitor(0,0, "init"); + assertScriptMonitor(0, 0, "init"); // WHEN, THEN long etimeFirst = executeScript("expression-string-variables.xml", "FOOBAR", "first"); - assertScriptMonitor(1,1, "first"); + assertScriptMonitor(1, 1, "first"); long etimeSecond = executeScript("expression-string-variables.xml", "FOOBAR", "second"); - assertScriptMonitor(1,2, "second"); - assertTrue("Einstein was wrong! "+etimeFirst+" -> "+etimeSecond, etimeSecond <= etimeFirst); + assertScriptMonitor(1, 2, "second"); + assertTrue("Einstein was wrong! " + etimeFirst + " -> " + etimeSecond, etimeSecond <= etimeFirst); long etimeThird = executeScript("expression-string-variables.xml", "FOOBAR", "second"); - assertScriptMonitor(1,3, "third"); - assertTrue("Einstein was wrong again! "+etimeFirst+" -> "+etimeThird, etimeThird <= etimeFirst); + assertScriptMonitor(1, 3, "third"); + assertTrue("Einstein was wrong again! " + etimeFirst + " -> " + etimeThird, etimeThird <= etimeFirst); // Different script. Should compile. long horatio1Time = executeScript("expression-func-concatname.xml", "Horatio Torquemada Marley", "horatio"); - assertScriptMonitor(2,4, "horatio"); + assertScriptMonitor(2, 4, "horatio"); // Same script. No compilation. long etimeFourth = executeScript("expression-string-variables.xml", "FOOBAR", "fourth"); - assertScriptMonitor(2,5, "fourth"); - assertTrue("Einstein was wrong all the time! "+etimeFirst+" -> "+etimeFourth, etimeFourth <= etimeFirst); + assertScriptMonitor(2, 5, "fourth"); + assertTrue("Einstein was wrong all the time! " + etimeFirst + " -> " + etimeFourth, etimeFourth <= etimeFirst); // Try this again. No compile. long horatio2Time = executeScript("expression-func-concatname.xml", "Horatio Torquemada Marley", "horatio2"); - assertScriptMonitor(2,6, "horatio2"); - assertTrue("Even Horatio was wrong! "+horatio1Time+" -> "+horatio2Time, horatio2Time <= horatio1Time); + assertScriptMonitor(2, 6, "horatio2"); + assertTrue("Even Horatio was wrong! " + horatio1Time + " -> " + horatio2Time, horatio2Time <= horatio1Time); } private void assertScriptMonitor(int expCompilations, int expExecutions, String desc) { - assertEquals("Unexpected number of script compilations after "+desc, expCompilations, InternalMonitor.getCount(InternalCounters.SCRIPT_COMPILE_COUNT)); - assertEquals("Unexpected number of script executions after "+desc, expExecutions, InternalMonitor.getCount(InternalCounters.SCRIPT_EXECUTION_COUNT)); + assertEquals("Unexpected number of script compilations after " + desc, expCompilations, InternalMonitor.getCount(InternalCounters.SCRIPT_COMPILE_COUNT)); + assertEquals("Unexpected number of script executions after " + desc, expExecutions, InternalMonitor.getCount(InternalCounters.SCRIPT_EXECUTION_COUNT)); } - private long executeScript(String filname, String expectedResult, String desc) throws SchemaException, IOException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + private long executeScript(String filname, String expectedResult, String desc) + throws SchemaException, SecurityViolationException, ExpressionEvaluationException, + ObjectNotFoundException, CommunicationException, ConfigurationException, IOException { // GIVEN - OperationResult result = new OperationResult(desc); + OperationResult result = createOperationResult(desc); ScriptExpressionEvaluatorType scriptType = parseScriptType(filname); ItemDefinition outputDefinition = getPrismContext().definitionFactory().createPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_STRING); @@ -145,20 +144,22 @@ private long executeScript(String filname, String expectedResult, String desc) t // WHEN long startTime = System.currentTimeMillis(); - List> scripResults = scriptExpression.evaluate(variables , null, false, desc, null, result); + List> scripResults = + scriptExpression.evaluate(variables, null, false, desc, null, result); long endTime = System.currentTimeMillis(); // THEN - System.out.println("Script results "+desc+", etime: "+(endTime - startTime)+" ms"); + System.out.println("Script results " + desc + ", etime: " + (endTime - startTime) + " ms"); System.out.println(scripResults); String scriptResult = asScalarString(scripResults); - assertEquals("Wrong script "+desc+" result", expectedResult, scriptResult); + assertEquals("Wrong script " + desc + " result", expectedResult, scriptResult); return (endTime - startTime); } - private ScriptExpression createScriptExpression(ScriptExpressionEvaluatorType expressionType, ItemDefinition outputDefinition) { + private ScriptExpression createScriptExpression( + ScriptExpressionEvaluatorType expressionType, ItemDefinition outputDefinition) { ScriptExpression expression = new ScriptExpression(scriptExpressionfactory.getEvaluators().get(expressionType.getLanguage()), expressionType); expression.setOutputDefinition(outputDefinition); expression.setObjectResolver(scriptExpressionfactory.getObjectResolver()); @@ -166,15 +167,15 @@ private ScriptExpression createScriptExpression(ScriptExpressionEvaluatorType ex return expression; } - private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws SchemaException, IOException { - ScriptExpressionEvaluatorType expressionType = PrismTestUtil.parseAtomicValue( + private ScriptExpressionEvaluatorType parseScriptType(String fileName) + throws SchemaException, IOException { + return PrismTestUtil.parseAtomicValue( new File(TEST_DIR, fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE); - return expressionType; } private String asScalarString(List> expressionResultList) { if (expressionResultList.size() > 1) { - AssertJUnit.fail("Expression produces a list of "+expressionResultList.size()+" while only expected a single value: "+expressionResultList); + AssertJUnit.fail("Expression produces a list of " + expressionResultList.size() + " while only expected a single value: " + expressionResultList); } if (expressionResultList.isEmpty()) { return null; diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java index e0c31f92940..f86032812f8 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java @@ -6,7 +6,6 @@ */ package com.evolveum.midpoint.model.common.expression.script; -import com.evolveum.midpoint.repo.common.expression.ExpressionVariables; import com.evolveum.midpoint.model.common.expression.script.velocity.VelocityScriptEvaluator; import com.evolveum.midpoint.prism.PrimitiveType; import com.evolveum.midpoint.prism.PrismContext; @@ -18,7 +17,6 @@ import org.testng.annotations.Test; -import javax.xml.namespace.QName; import java.io.File; /** @@ -39,7 +37,7 @@ protected File getTestDir() { @Test public void testExpressionList() throws Exception { - evaluateAndAssertStringScalarExpresssion( // velocity has no support for output other than String + evaluateAndAssertStringScalarExpression( // velocity has no support for output other than String "expression-list.xml", "testExpressionList", createVariables( @@ -53,7 +51,7 @@ public void testExpressionList() throws Exception { @Test public void testExpressionPolyStringEquals101() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals101", createVariables( @@ -65,7 +63,7 @@ public void testExpressionPolyStringEquals101() throws Exception { @Test public void testExpressionPolyStringEquals102() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals102", createVariables( @@ -77,7 +75,7 @@ public void testExpressionPolyStringEquals102() throws Exception { @Test public void testExpressionPolyStringEquals111() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals111", createVariables( @@ -89,7 +87,7 @@ public void testExpressionPolyStringEquals111() throws Exception { @Test public void testExpressionPolyStringEquals112() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals112", createVariables( @@ -101,7 +99,7 @@ public void testExpressionPolyStringEquals112() throws Exception { @Test public void testExpressionPolyStringEquals121() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals121", createVariables( @@ -113,7 +111,7 @@ public void testExpressionPolyStringEquals121() throws Exception { @Test public void testExpressionPolyStringEquals122() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-1.xml", "testExpressionPolyStringEquals122", createVariables( @@ -125,7 +123,7 @@ public void testExpressionPolyStringEquals122() throws Exception { @Test public void testExpressionPolyStringEquals201() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals201", createVariables( @@ -137,7 +135,7 @@ public void testExpressionPolyStringEquals201() throws Exception { @Test public void testExpressionPolyStringEquals202() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals202", createVariables( @@ -149,7 +147,7 @@ public void testExpressionPolyStringEquals202() throws Exception { @Test public void testExpressionPolyStringEquals211() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals211", createVariables( @@ -161,7 +159,7 @@ public void testExpressionPolyStringEquals211() throws Exception { @Test public void testExpressionPolyStringEquals212() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals212", createVariables( @@ -173,7 +171,7 @@ public void testExpressionPolyStringEquals212() throws Exception { @Test public void testExpressionPolyStringEquals221() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals221", createVariables( @@ -185,7 +183,7 @@ public void testExpressionPolyStringEquals221() throws Exception { @Test public void testExpressionPolyStringEquals222() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-2.xml", "testExpressionPolyStringEquals222", createVariables( @@ -197,7 +195,7 @@ public void testExpressionPolyStringEquals222() throws Exception { @Test public void testExpressionPolyStringEqualsStringify101() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify101", createVariables( @@ -209,7 +207,7 @@ public void testExpressionPolyStringEqualsStringify101() throws Exception { @Test public void testExpressionPolyStringEqualsStringify102() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify102", createVariables( @@ -221,7 +219,7 @@ public void testExpressionPolyStringEqualsStringify102() throws Exception { @Test public void testExpressionPolyStringEqualsStringify111() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify111", createVariables( @@ -233,7 +231,7 @@ public void testExpressionPolyStringEqualsStringify111() throws Exception { @Test public void testExpressionPolyStringEqualsStringify112() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify112", createVariables( @@ -245,7 +243,7 @@ public void testExpressionPolyStringEqualsStringify112() throws Exception { @Test public void testExpressionPolyStringEqualsStringify121() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify121", createVariables( @@ -257,7 +255,7 @@ public void testExpressionPolyStringEqualsStringify121() throws Exception { @Test public void testExpressionPolyStringEqualsStringify122() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-1.xml", "testExpressionPolyStringEqualsStringify122", createVariables( @@ -269,7 +267,7 @@ public void testExpressionPolyStringEqualsStringify122() throws Exception { @Test public void testExpressionPolyStringEqualsStringify201() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify201", createVariables( @@ -281,7 +279,7 @@ public void testExpressionPolyStringEqualsStringify201() throws Exception { @Test public void testExpressionPolyStringEqualsStringify202() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify202", createVariables( @@ -293,7 +291,7 @@ public void testExpressionPolyStringEqualsStringify202() throws Exception { @Test public void testExpressionPolyStringEqualsStringify211() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify211", createVariables( @@ -305,7 +303,7 @@ public void testExpressionPolyStringEqualsStringify211() throws Exception { @Test public void testExpressionPolyStringEqualsStringify212() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify212", createVariables( @@ -317,7 +315,7 @@ public void testExpressionPolyStringEqualsStringify212() throws Exception { @Test public void testExpressionPolyStringEqualsStringify221() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify221", createVariables( @@ -329,7 +327,7 @@ public void testExpressionPolyStringEqualsStringify221() throws Exception { @Test public void testExpressionPolyStringEqualsStringify222() throws Exception { - evaluateAndAssertBooleanScalarExpresssion( + evaluateAndAssertBooleanScalarExpression( "expression-polystring-equals-stringify-2.xml", "testExpressionPolyStringEqualsStringify222", createVariables( diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java index be36ce70555..3573f278493 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java @@ -11,62 +11,46 @@ import java.io.File; import java.io.IOException; import java.util.Collection; - import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; +import org.xml.sax.SAXException; + +import com.evolveum.midpoint.common.Clock; +import com.evolveum.midpoint.model.common.expression.ExpressionTestUtil; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.crypto.EncryptionException; import com.evolveum.midpoint.prism.crypto.Protector; -import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.task.api.test.NullTaskImpl; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; - -import org.xml.sax.SAXException; - +import com.evolveum.midpoint.prism.util.ObjectDeltaObject; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.common.DirectoryFileObjectResolver; import com.evolveum.midpoint.repo.common.ObjectResolver; import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import com.evolveum.midpoint.repo.common.expression.Source; import com.evolveum.midpoint.repo.common.expression.ValuePolicyResolver; -import com.evolveum.midpoint.common.Clock; -import com.evolveum.midpoint.model.common.expression.ExpressionTestUtil; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.OriginType; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.PrismPropertyDefinition; -import com.evolveum.midpoint.prism.PrismPropertyValue; -import com.evolveum.midpoint.prism.crypto.EncryptionException; -import com.evolveum.midpoint.prism.util.ObjectDeltaObject; -import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.test.NullTaskImpl; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * The class that takes care of all the ornaments of value construction execution. It is used to make the * tests easy to write. * * @author Radovan Semancik - * */ public class MappingTestEvaluator { @@ -107,42 +91,53 @@ public Protector getProtector() { return protector; } - public MappingImpl, PrismPropertyDefinition> createMapping(String filename, String testName, final ValuePolicyType policy, String defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { + public MappingImpl, PrismPropertyDefinition> createMapping( + String filename, String testName, final ValuePolicyType policy, + String defaultTargetPropertyName, ObjectDelta userDelta) + throws SchemaException, IOException, EncryptionException { return this.createMappingBuilder(filename, testName, policy, toPath(defaultTargetPropertyName), userDelta).build(); } - public MappingImpl, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, - ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { + public MappingImpl, PrismPropertyDefinition> createMapping( + String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta) + throws SchemaException, IOException, EncryptionException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta).build(); } - public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, String defaultTargetPropertyName, - ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { + public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder( + String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta) + throws SchemaException, IOException, EncryptionException { return createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta); } - public MappingImpl, PrismPropertyDefinition> createMapping(String filename, String testName, ItemName defaultTargetPropertyName, - ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { + public MappingImpl, PrismPropertyDefinition> createMapping( + String filename, String testName, ItemName defaultTargetPropertyName, ObjectDelta userDelta) + throws SchemaException, IOException, EncryptionException { return this.createMappingBuilder(filename, testName, null, defaultTargetPropertyName, userDelta).build(); } - public MappingImpl, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, - ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException, JAXBException { + public MappingImpl, PrismPropertyDefinition> createMapping( + String filename, String testName, String defaultTargetPropertyName, + ObjectDelta userDelta, PrismObject userOld) + throws SchemaException, IOException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta, userOld).build(); } public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, String defaultTargetPropertyName, - ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException, JAXBException { + ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta, userOld); } - public MappingImpl, PrismPropertyDefinition> createMapping(String filename, String testName, ItemPath defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { + public MappingImpl, PrismPropertyDefinition> createMapping( + String filename, String testName, ItemPath defaultTargetPropertyName, ObjectDelta userDelta) + throws SchemaException, IOException, EncryptionException { return this.createMappingBuilder(filename, testName, null, defaultTargetPropertyName, userDelta).build(); } - public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, final ValuePolicyType policy, + public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder( + String filename, String testName, final ValuePolicyType policy, ItemPath defaultTargetPropertyPath, ObjectDelta userDelta) - throws SchemaException, IOException, JAXBException, EncryptionException { + throws SchemaException, IOException, EncryptionException { PrismObject userOld = null; if (userDelta == null || !userDelta.isAdd()) { userOld = getUserOld(); @@ -150,18 +145,22 @@ public MappingImpl.Builder, PrismPropertyDefinition return createMappingBuilder(filename, testName, policy, defaultTargetPropertyPath, userDelta, userOld); } - public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, final ValuePolicyType policy, - ItemPath defaultTargetPropertyPath, ObjectDelta userDelta, PrismObject userOld) - throws SchemaException, IOException, JAXBException { - + public MappingImpl.Builder, PrismPropertyDefinition> createMappingBuilder( + String filename, String testName, final ValuePolicyType policy, ItemPath defaultTargetPropertyPath, + ObjectDelta userDelta, PrismObject userOld) + throws SchemaException, IOException { MappingType mappingType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, filename), MappingType.COMPLEX_TYPE); - MappingImpl.Builder,PrismPropertyDefinition> mappingBuilder = mappingFactory.createMappingBuilder(mappingType, testName); + MappingImpl.Builder, PrismPropertyDefinition> mappingBuilder = + mappingFactory.createMappingBuilder(mappingType, testName); mappingBuilder.prismContext(prismContext); // Source context: user - ObjectDeltaObject userOdo = new ObjectDeltaObject<>(userOld, userDelta, null, prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class)); + PrismObjectDefinition objectDefinition = + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); + ObjectDeltaObject userOdo = + new ObjectDeltaObject<>(userOld, userDelta, null, objectDefinition); userOdo.recompute(); mappingBuilder.sourceContext(userOdo); @@ -171,7 +170,8 @@ public MappingImpl.Builder, PrismPropertyDefinition // Variable $projection PrismObject account = getAccount(); - ObjectDeltaObject accountOdo = new ObjectDeltaObject<>(account, null, null, account.getDefinition()); + ObjectDeltaObject accountOdo = + new ObjectDeltaObject<>(account, null, null, account.getDefinition()); accountOdo.recompute(); mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_PROJECTION, accountOdo); mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, accountOdo); @@ -180,7 +180,6 @@ public MappingImpl.Builder, PrismPropertyDefinition PrismObjectDefinition userDefinition = getUserDefinition(); mappingBuilder.targetContext(userDefinition); - ValuePolicyResolver stringPolicyResolver = new ValuePolicyResolver() { ItemPath outputPath; ItemDefinition outputDefinition; @@ -206,7 +205,7 @@ public ValuePolicyType resolve() { if (defaultTargetPropertyPath != null) { PrismPropertyDefinition targetDefDefinition = userDefinition.findItemDefinition(defaultTargetPropertyPath); if (targetDefDefinition == null) { - throw new IllegalArgumentException("The item path '"+defaultTargetPropertyPath+"' does not have a definition in "+userDefinition); + throw new IllegalArgumentException("The item path '" + defaultTargetPropertyPath + "' does not have a definition in " + userDefinition); } mappingBuilder.setDefaultTargetDefinition(targetDefDefinition); } @@ -214,15 +213,17 @@ public ValuePolicyType resolve() { return mappingBuilder; } - public MappingImpl, PrismPropertyDefinition> createInboudMapping(String filename, String testName, ItemDelta delta, UserType user, ShadowType account, ResourceType resource, final ValuePolicyType policy) throws SchemaException, IOException, JAXBException{ + public MappingImpl, PrismPropertyDefinition> createInboudMapping( + String filename, String testName, ItemDelta delta, UserType user, ShadowType account, + ResourceType resource, final ValuePolicyType policy) + throws SchemaException, IOException { MappingType mappingType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, filename), MappingType.COMPLEX_TYPE); - MappingImpl.Builder,PrismPropertyDefinition> builder = mappingFactory.createMappingBuilder(mappingType, testName); + MappingImpl.Builder, PrismPropertyDefinition> builder = mappingFactory.createMappingBuilder(mappingType, testName); - - Source,PrismPropertyDefinition> defaultSource = new Source<>(null, delta, null, ExpressionConstants.VAR_INPUT_QNAME, delta.getDefinition()); + Source, PrismPropertyDefinition> defaultSource = new Source<>(null, delta, null, ExpressionConstants.VAR_INPUT_QNAME, delta.getDefinition()); defaultSource.recompute(); builder.setDefaultSource(defaultSource); builder.setTargetContext(getUserDefinition()); @@ -275,10 +276,13 @@ public PrismObjectDefinition getUserDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, - ItemPath defaultTargetPropertyPath) - throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyPath, null); + public PrismValueDeltaSetTriple> evaluateMapping( + String filename, String testName, ItemPath defaultTargetPropertyPath) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyPath, null); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -289,10 +293,13 @@ public PrismValueDeltaSetTriple> evaluateMapping(Str return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, - ItemName defaultTargetPropertyName) - throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, null); + public PrismValueDeltaSetTriple> evaluateMapping( + String filename, String testName, ItemName defaultTargetPropertyName) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, null); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -303,10 +310,13 @@ public PrismValueDeltaSetTriple> evaluateMapping(Str return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, - String defaultTargetPropertyName) - throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, null); + public PrismValueDeltaSetTriple> evaluateMapping( + String filename, String testName, String defaultTargetPropertyName) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, null); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -326,19 +336,27 @@ public void assertResult(OperationResult opResult) { TestUtil.assertSuccess(opResult); } - public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, - String defaultTargetPropertyName, - String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - return evaluateMappingDynamicAdd(filename, testName, toPath(defaultTargetPropertyName), changedPropertyName, valuesToAdd); - } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, - ItemPath defaultTargetPropertyPath, - String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createModificationAddProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), - valuesToAdd); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyPath, userDelta); + public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd( + String filename, String testName, String defaultTargetPropertyName, + String changedPropertyName, I... valuesToAdd) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + return evaluateMappingDynamicAdd(filename, testName, + toPath(defaultTargetPropertyName), changedPropertyName, valuesToAdd); + } + + public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd( + String filename, String testName, ItemPath defaultTargetPropertyPath, + String changedPropertyName, I... valuesToAdd) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationAddProperty( + UserType.class, USER_OLD_OID, toPath(changedPropertyName), valuesToAdd); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyPath, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -349,13 +367,17 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMappingDynamicDelete(String filename, String testName, - String defaultTargetPropertyName, - String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createModificationDeleteProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), - valuesToAdd); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); + public PrismValueDeltaSetTriple> evaluateMappingDynamicDelete( + String filename, String testName, String defaultTargetPropertyName, + String changedPropertyName, I... valuesToAdd) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationDeleteProperty( + UserType.class, USER_OLD_OID, toPath(changedPropertyName), valuesToAdd); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -366,13 +388,17 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, - String defaultTargetPropertyName, - String changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), - valuesToReplace); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace( + String filename, String testName, String defaultTargetPropertyName, + String changedPropertyName, I... valuesToReplace) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationReplaceProperty( + UserType.class, USER_OLD_OID, toPath(changedPropertyName), valuesToReplace); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -383,13 +409,17 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, - String defaultTargetPropertyName, - ItemPath changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, - valuesToReplace); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace( + String filename, String testName, String defaultTargetPropertyName, + ItemPath changedPropertyName, I... valuesToReplace) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationReplaceProperty( + UserType.class, USER_OLD_OID, changedPropertyName, valuesToReplace); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -400,13 +430,17 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, - ItemPath defaultTargetPropertyName, - String changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), - valuesToReplace); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace( + String filename, String testName, ItemPath defaultTargetPropertyName, + String changedPropertyName, I... valuesToReplace) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationReplaceProperty( + UserType.class, USER_OLD_OID, toPath(changedPropertyName), valuesToReplace); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); @@ -418,13 +452,17 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna return outputTriple; } - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, - ItemPath defaultTargetPropertyName, - ItemPath changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException, SecurityViolationException, ConfigurationException, CommunicationException { + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace( + String filename, String testName, ItemPath defaultTargetPropertyName, + ItemPath changedPropertyName, I... valuesToReplace) + throws SchemaException, IOException, ExpressionEvaluationException, + ObjectNotFoundException, EncryptionException, SecurityViolationException, + ConfigurationException, CommunicationException { ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, valuesToReplace); - MappingImpl,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); + MappingImpl, PrismPropertyDefinition> mapping = + createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); mapping.evaluate(new NullTaskImpl(), opResult); assertResult(opResult); @@ -440,7 +478,7 @@ public ItemPath toPath(String propertyName) { } public static T getSingleValue(String setName, Collection> set) { - assertEquals("Expected single value in "+setName+" but found "+set.size()+" values: "+set, 1, set.size()); + assertEquals("Expected single value in " + setName + " but found " + set.size() + " values: " + set, 1, set.size()); PrismPropertyValue propertyValue = set.iterator().next(); return propertyValue.getValue(); } @@ -454,15 +492,13 @@ public Object createProtectedString(String string) throws EncryptionException { return protector.encryptString(string); } - public void assertProtectedString(String desc, - Collection> set, - String expected) throws EncryptionException { - assertEquals("Unexpected size of "+desc+": "+set, 1, set.size()); + public void assertProtectedString( + String desc, Collection> set, String expected) + throws EncryptionException { + assertEquals("Unexpected size of " + desc + ": " + set, 1, set.size()); PrismPropertyValue pval = set.iterator().next(); ProtectedStringType ps = pval.getValue(); String zeroString = protector.decryptString(ps); - assertEquals("Unexpected value in "+desc+": "+set, expected, zeroString); - + assertEquals("Unexpected value in " + desc + ": " + set, expected, zeroString); } - } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java index 9e0c05a5932..9f895763fb4 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java @@ -23,7 +23,6 @@ import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -46,50 +45,46 @@ public void setupFactory() throws SAXException, IOException, SchemaException { public void testModifyObjectSetAdditionalName() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - UserType.F_ADDITIONAL_NAME, "Jackie"); + .createModificationReplaceProperty(UserType.class, + MappingTestEvaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "321"); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (#321)")); - PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (#null)")); + PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (#321)")); + PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (#null)")); } @Test public void testModifyObjectSetAdditionalNameFalse() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - UserType.F_ADDITIONAL_NAME, "Jackie"); + .createModificationReplaceProperty(UserType.class, + MappingTestEvaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "321"); PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().getEmployeeType().clear(); userOld.asObjectable().getEmployeeType().add("WHATEVER"); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta, userOld); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); - assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); + assertNull("Unexpected value in outputTriple: " + outputTriple, outputTriple); } /** @@ -99,48 +94,44 @@ public void testModifyObjectSetAdditionalNameFalse() throws Exception { public void testModifyObjectUnrelated() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - evaluator.toPath("costCenter"), "X606"); + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, + evaluator.toPath("costCenter"), "X606"); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("Pirate null (#null)")); - PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoPlus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @Test public void testModifyObjectUnrelatedFalse() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - evaluator.toPath("costCenter"), "X606"); + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, + evaluator.toPath("costCenter"), "X606"); PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().getEmployeeType().clear(); userOld.asObjectable().getEmployeeType().add("WHATEVER"); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta, userOld); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); - assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); + assertNull("Unexpected value in outputTriple: " + outputTriple, outputTriple); } @Test @@ -151,18 +142,16 @@ public void testAddObjectUnrelatedFalse() throws Exception { user.asObjectable().getEmployeeType().add("WHATEVER"); ObjectDelta delta = user.createAddDelta(); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); - assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); + assertNull("Unexpected value in outputTriple: " + outputTriple, outputTriple); } @Test @@ -172,17 +161,15 @@ public void testAddObjectUnrelatedEmptyFalse() throws Exception { user.asObjectable().getEmployeeType().clear(); ObjectDelta delta = user.createAddDelta(); - MappingImpl,PrismPropertyDefinition> mapping = evaluator.createMapping( + MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_COMPLEX_FILENAME, getTestNameShort(), "title", delta); - OperationResult opResult = new OperationResult(contextName()); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); - assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); + assertNull("Unexpected value in outputTriple: " + outputTriple, outputTriple); } } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java index fc6445e5912..10c9620a5dc 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java @@ -6,8 +6,6 @@ */ package com.evolveum.midpoint.model.common.mapping; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.io.IOException; import java.util.List; @@ -26,7 +24,9 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.test.NullTaskImpl; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -37,7 +37,8 @@ * * @author Radovan Semancik */ -public class TestMappingDomain extends AbstractUnitTest { +public class TestMappingDomain extends AbstractUnitTest + implements OperationResultTestMixin { private static final String MAPPING_DOMAIN_FILENAME = "mapping-domain.xml"; @@ -69,7 +70,7 @@ public void testControlReplaceSingleValue() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(MAPPING_DOMAIN_FILENAME, getTestNameShort(), "organization", delta, userOld); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -104,12 +105,11 @@ public void testControlReplaceMultiValue() throws Exception { UserType.F_ADDITIONAL_NAME, "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, "991", "992"); - String shortTestName = getTestNameShort(); MappingImpl, PrismPropertyDefinition> mapping = - evaluator.createMapping(MAPPING_DOMAIN_FILENAME, shortTestName, "organization", delta, userOld); + evaluator.createMapping(MAPPING_DOMAIN_FILENAME, getTestNameShort(), "organization", delta, userOld); // WHEN - mapping.evaluate(createTask(), new OperationResult(shortTestName)); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -146,7 +146,7 @@ public void testReplaceMixedMultiValue() throws Exception { evaluator.createMapping( MAPPING_DOMAIN_FILENAME, shortTestName, "organization", delta, userOld); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN when(); @@ -188,7 +188,7 @@ public void testAddMixedMultiValue() throws Exception { evaluator.createMapping( MAPPING_DOMAIN_FILENAME, shortTestName, "organization", delta, userOld); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN when(); @@ -232,7 +232,7 @@ public void testDeleteMixedMultiValue() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( MAPPING_DOMAIN_FILENAME, shortTestName, "organization", delta, userOld); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN when(); @@ -252,4 +252,11 @@ public void testDeleteMixedMultiValue() throws Exception { PrismTestUtil.createPolyString("Pirate Jackie (007)")); } + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java index b9abafbe4b9..fff0f03b674 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java @@ -11,7 +11,6 @@ import static com.evolveum.midpoint.prism.util.PrismAsserts.assertTripleNoMinus; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertTripleZero; import static com.evolveum.midpoint.schema.constants.SchemaConstants.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; import java.io.File; import java.io.IOException; @@ -65,7 +64,7 @@ public void testValueSingleDeep() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-single-deep.xml", - "testValue", + getTestNameShort(), "costCenter", // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -82,7 +81,7 @@ public void testValueSingleShallow() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-single-shallow.xml", - "testValue", + getTestNameShort(), "costCenter", // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -99,7 +98,7 @@ public void testValueMultiDeep() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-multi-deep.xml", - "testValueMulti", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -116,7 +115,7 @@ public void testValueMultiShallow() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-multi-shallow.xml", - "testValueMulti", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -133,7 +132,7 @@ public void testValueSingleEnum() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-single-enum.xml", - "testValueSingleEnum", + getTestNameShort(), PATH_ACTIVATION_ADMINISTRATIVE_STATUS, // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -150,7 +149,7 @@ public void testAsIsAdd() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-asis.xml", - "testAsIsAdd", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -167,7 +166,7 @@ public void testAsIsDelete() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicDelete( "mapping-asis.xml", - "testAsIsDelete", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "PIRATE"); // changed values @@ -183,9 +182,7 @@ public void testAsIsDelete() throws Exception { public void testAsIsStringToPolyString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-asis.xml", - "testAsIsStringToPolyString", - "fullName"); // target + "mapping-asis.xml", getTestNameShort(), "fullName"); // THEN outputTriple.checkConsistence(); @@ -197,10 +194,9 @@ public void testAsIsStringToPolyString() throws Exception { @Test public void testAsIsStringToProtectedString() throws Exception { // WHEN - PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-asis.xml", - "testAsIsStringToProtectedString", - PATH_CREDENTIALS_PASSWORD_VALUE); // target + PrismValueDeltaSetTriple> outputTriple = + evaluator.evaluateMapping( + "mapping-asis.xml", getTestNameShort(), PATH_CREDENTIALS_PASSWORD_VALUE); // THEN outputTriple.checkConsistence(); @@ -212,10 +208,9 @@ public void testAsIsStringToProtectedString() throws Exception { @Test public void testAsIsProtectedStringToProtectedString() throws Exception { // WHEN - PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-asis-password.xml", - "testAsIsProtectedStringToProtectedString", - PATH_CREDENTIALS_PASSWORD_VALUE); // target + PrismValueDeltaSetTriple> outputTriple = + evaluator.evaluateMapping( + "mapping-asis-password.xml", getTestNameShort(), PATH_CREDENTIALS_PASSWORD_VALUE); // THEN outputTriple.checkConsistence(); @@ -228,9 +223,7 @@ public void testAsIsProtectedStringToProtectedString() throws Exception { public void testAsIsProtectedStringToString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-asis-password.xml", - "testAsIsProtectedStringToString", - UserType.F_EMPLOYEE_NUMBER); // target + "mapping-asis-password.xml", getTestNameShort(), UserType.F_EMPLOYEE_NUMBER); // THEN outputTriple.checkConsistence(); @@ -243,9 +236,7 @@ public void testAsIsProtectedStringToString() throws Exception { public void testAsIsProtectedStringToPolyString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-asis-password.xml", - "testAsIsProtectedStringToPolyString", - UserType.F_FULL_NAME); // target + "mapping-asis-password.xml", getTestNameShort(), UserType.F_FULL_NAME); // target // THEN outputTriple.checkConsistence(); @@ -259,7 +250,7 @@ public void testPathVariables() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables.xml", - "testPathVariables", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -275,10 +266,7 @@ public void testPathVariables() throws Exception { public void testPathExtensionProperty() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-path-extension-variable.xml", - "testPathExtensionProperty", - ShadowType.F_NAME // target - ); // changed values + "mapping-path-extension-variable.xml", getTestNameShort(), ShadowType.F_NAME); // THEN outputTriple.checkConsistence(); @@ -290,7 +278,7 @@ public void testPathVariablesNamespace() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables-namespace.xml", - "testPathVariablesNamespace", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -307,7 +295,7 @@ public void testPathVariablesPolyStringShort() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables-polystring-short.xml", - "testPathVariablesPolyStringShort", + getTestNameShort(), "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -324,7 +312,7 @@ public void testPathVariablesPolyStringToStringShort() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables-polystring-short.xml", - "testPathVariablesPolyStringToStringShort", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -341,7 +329,7 @@ public void testPathVariablesExtension() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables-polystring-long.xml", - "testPathVariablesPolyStringToStringLong", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -358,7 +346,7 @@ public void testPathVariablesPolyStringToStringLong() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-path-system-variables-polystring-long.xml", - "testPathVariablesPolyStringToStringLong", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -375,7 +363,7 @@ public void testScriptSimpleGroovy() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-simple-groovy.xml", - "testScriptSimpleGroovy", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -392,7 +380,7 @@ public void testScriptVariablesGroovy() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-variables-groovy.xml", - "testScriptVariablesGroovy", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -409,7 +397,7 @@ public void testScriptVariablesPolyStringGroovy() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-system-variables-polystring-groovy.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -426,7 +414,7 @@ public void testScriptVariablesPolyStringGroovyOp() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-system-variables-polystring-groovy-op.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -443,7 +431,7 @@ public void testScriptVariablesPolyStringGroovyOrig() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-system-variables-polystring-groovy-orig.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -460,7 +448,7 @@ public void testScriptVariablesPolyStringGroovyNorm() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-system-variables-polystring-groovy-norm.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -476,7 +464,7 @@ public void testScriptVariablesPolyStringGroovyNormReplace() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-polystring-groovy-norm.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "fullName", // changed property PrismTestUtil.createPolyString("Barbossa")); // changed values @@ -493,7 +481,7 @@ public void testScriptVariablesPolyStringGroovyNormReplaceNull() throws Exceptio // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-polystring-groovy-norm.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "fullName" // changed property ); // changed values @@ -510,7 +498,7 @@ public void testAsIsVariablesPolyStringNorm() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-asis-system-variables-polystring-norm.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -527,7 +515,7 @@ public void testAsIsVariablesPolyStringOrig() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-asis-system-variables-polystring-orig.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values @@ -556,10 +544,8 @@ public void testScriptExtraVariablesRef() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult("testScriptExtraVariablesRef"); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -572,10 +558,9 @@ public void testScriptExtraVariablesRef() throws Exception { @Test public void testScriptExtraVariablesJaxb() throws Exception { // GIVEN - String shortTestName = getTestNameShort(); MappingImpl.Builder, PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - "mapping-script-extra-variables.xml", shortTestName, "employeeType", null); + "mapping-script-extra-variables.xml", getTestNameShort(), "employeeType", null); VariablesMap vars = new VariablesMap(); UserType userType = (UserType) PrismTestUtil.parseObject( @@ -584,10 +569,8 @@ public void testScriptExtraVariablesJaxb() throws Exception { builder.addVariableDefinitions(vars); MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(shortTestName); - // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -601,9 +584,7 @@ public void testScriptExtraVariablesJaxb() throws Exception { public void testScriptFullNameNoChange() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-script-fullname.xml", - "testScriptVariablesPolyStringGroovy", - "fullName"); // target + "mapping-script-fullname.xml", getTestNameShort(), "fullName"); // THEN outputTriple.checkConsistence(); @@ -615,10 +596,9 @@ public void testScriptFullNameNoChange() throws Exception { @Test public void testScriptFullNameReplaceGivenName() throws Exception { // WHEN - String shortTestName = getTestNameShort(); PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-fullname.xml", - shortTestName, + getTestNameShort(), "fullName", // target "givenName", // changed property PrismTestUtil.createPolyString("Jackie")); // changed values @@ -646,7 +626,7 @@ public void testScriptFullNameDeleteGivenName() throws Exception { "fullName", // target delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -676,7 +656,7 @@ public void testScriptFullNameDeleteGivenNameFromNull() throws Exception { "fullName", // target delta, userOld); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -704,7 +684,7 @@ public void testScriptFullNameDeleteGivenNameFamilyName() throws Exception { "fullName", // target delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -725,7 +705,7 @@ public void testScriptFullNameReplaceEmployeeNumber() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-fullname.xml", - "testScriptVariablesPolyStringGroovy", + getTestNameShort(), "fullName", // target "employeeNumber", // changed property "666"); // changed values @@ -745,7 +725,7 @@ public void testScriptDateGroovy() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-date-groovy.xml", - "testScriptDateGroovy", + getTestNameShort(), PATH_ACTIVATION_VALID_FROM, // target "employeeNumber", // changed property "1975-05-30"); // changed values @@ -762,7 +742,7 @@ public void testScriptCustomEnum() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-custom-enum.xml", - "testScriptCustomEnum", + getTestNameShort(), ItemPath.create(UserType.F_EXTENSION, new QName("tShirtSize")), // target "employeeType", // changed property "CAPTAIN"); // changed values @@ -779,7 +759,7 @@ public void testScriptListRelativeGroovy() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-script-list-relative-groovy.xml", - "testScriptListRelativeGroovy", + getTestNameShort(), "organizationalUnit", // target "organizationalUnit", // changed property PrismTestUtil.createPolyString("Antropomorphic Personifications")); // changed values @@ -802,7 +782,7 @@ public void testScriptListAbsolute(String fileName) throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( fileName, - "testScriptListAbsolute", + getTestNameShort(), "organizationalUnit", // target "organizationalUnit", // changed property PrismTestUtil.createPolyString("Antropomorphic Personifications")); // changed values @@ -822,7 +802,7 @@ public void testValueConditionTrue() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-condition-true.xml", - "testValueConditionTrue", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "DRUNKARD"); // changed values @@ -839,7 +819,7 @@ public void testValueConditionFalse() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd( "mapping-value-condition-false.xml", - "testValueConditionFalse", + getTestNameShort(), "employeeType", // target "employeeType", // changed property "DRUNKARD"); // changed values @@ -861,7 +841,7 @@ public void testConditionNonEmptyCaptain() throws Exception { "mapping-condition-nonempty.xml", shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -887,7 +867,7 @@ public void testConditionNonEmptyEmpty() throws Exception { "mapping-condition-nonempty.xml", shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -909,7 +889,7 @@ public void testConditionNonEmptyNoValue() throws Exception { "mapping-condition-nonempty.xml", shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -940,11 +920,9 @@ public void testScriptTransformMultiAddDelete() throws Exception { display("user before", user); display("delta", delta); - OperationResult opResult = new OperationResult(shortTestName); - // WHEN when(); - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN then(); @@ -962,8 +940,7 @@ public void testScriptTransformMultiAddDelete() throws Exception { public void testScriptTransformMultiReplace() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createEmptyModifyDelta(UserType.class, MappingTestEvaluator.USER_OLD_OID - ); + .createEmptyModifyDelta(UserType.class, MappingTestEvaluator.USER_OLD_OID); PropertyDelta propDelta = delta.createPropertyModification(evaluator.toPath("employeeType")); propDelta.setRealValuesToReplace("CAPTAIN"); delta.addModification(propDelta); @@ -977,11 +954,9 @@ public void testScriptTransformMultiReplace() throws Exception { display("user before", user); display("delta", delta); - OperationResult opResult = new OperationResult(shortTestName); - // WHEN when(); - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN then(); @@ -1020,10 +995,8 @@ public void testInboundMapping() throws Exception { evaluator.createInboudMapping( "mapping-inbound.xml", shortTestName, delta, user.asObjectable(), account.asObjectable(), null, null); - OperationResult opResult = new OperationResult(shortTestName); - when(); - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -1041,10 +1014,8 @@ public void testGenerateDefault() throws Exception { evaluator.createMapping("mapping-generate.xml", shortTestName, stringPolicy, "employeeNumber", null); - OperationResult opResult = new OperationResult(shortTestName); - // WHEN (1) - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN (1) PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -1058,7 +1029,7 @@ public void testGenerateDefault() throws Exception { mapping = evaluator.createMapping("mapping-generate.xml", shortTestName, stringPolicy, "employeeNumber", null); // WHEN (2) - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN (2) outputTriple = mapping.getOutputTriple(); @@ -1074,21 +1045,18 @@ public void testGenerateDefault() throws Exception { @Test public void testGeneratePolicy() throws Exception { - final String TEST_NAME = "testGeneratePolicy"; - generatePolicy(TEST_NAME, "mapping-generate-policy.xml", "c0c010c0-d34d-b33f-f00d-999888111111.xml", null, false); + generatePolicy("mapping-generate-policy.xml", "c0c010c0-d34d-b33f-f00d-999888111111.xml", null, false); } @Test public void testGeneratePolicyEmpty() throws Exception { - final String TEST_NAME = "testGeneratePolicy"; - generatePolicy(TEST_NAME, "mapping-generate-policy-empty.xml", "c0c010c0-d34d-b33f-f00d-999888111114.xml", null, true); + generatePolicy("mapping-generate-policy-empty.xml", "c0c010c0-d34d-b33f-f00d-999888111114.xml", null, true); } @Test public void testGeneratePolicyBad() throws Exception { - final String TEST_NAME = "testGeneratePolicy"; try { - generatePolicy(TEST_NAME, "mapping-generate-policy-bad.xml", "c0c010c0-d34d-b33f-f00d-999888111113.xml", null, false); + generatePolicy("mapping-generate-policy-bad.xml", "c0c010c0-d34d-b33f-f00d-999888111113.xml", null, false); AssertJUnit.fail("Unexpected success"); } catch (ExpressionEvaluationException e) { // This is expected, the policy is broken @@ -1097,12 +1065,11 @@ public void testGeneratePolicyBad() throws Exception { @Test public void testGeneratePolicyNumericString() throws Exception { - final String TEST_NAME = "testGeneratePolicyNumericString"; - generatePolicy(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", - PATTERN_NUMERIC, false); + generatePolicy("mapping-generate-policy-numeric.xml", + "c0c010c0-d34d-b33f-f00d-999888111112.xml", PATTERN_NUMERIC, false); } - private void generatePolicy(final String TEST_NAME, String mappingFileName, String policyFileName, String pattern, boolean ignoreMax) + private void generatePolicy(String mappingFileName, String policyFileName, String pattern, boolean ignoreMax) throws Exception { // This is just for validation. The expression has to resolve reference of its own @@ -1110,13 +1077,12 @@ private void generatePolicy(final String TEST_NAME, String mappingFileName, Stri new File(MidPointTestConstants.OBJECTS_DIR, policyFileName)); final ValuePolicyType stringPolicy = valuePolicy.asObjectable(); // GIVEN - MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(mappingFileName, - TEST_NAME, stringPolicy, "employeeNumber", null); - - OperationResult opResult = new OperationResult(contextName()); + MappingImpl, PrismPropertyDefinition> mapping = + evaluator.createMapping( + mappingFileName, getTestNameShort(), stringPolicy, "employeeNumber", null); // WHEN (1) - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN (1) PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -1130,10 +1096,11 @@ private void generatePolicy(final String TEST_NAME, String mappingFileName, Stri assertGeneratedValue(value1, stringPolicy, pattern, false, ignoreMax); // GIVEN (2) - mapping = evaluator.createMapping(mappingFileName, TEST_NAME, stringPolicy, "employeeNumber", null); + mapping = evaluator.createMapping( + mappingFileName, getTestNameShort(), stringPolicy, "employeeNumber", null); // WHEN (2) - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN (2) outputTriple = mapping.getOutputTriple(); @@ -1168,26 +1135,23 @@ private void assertGeneratedValue(String value, ValuePolicyType valuePolicy, Str @Test public void testGeneratePolicyNumericInt() throws Exception { - final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric("mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "intType"); } @Test public void testGeneratePolicyNumericInteger() throws Exception { - final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric("mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "integerType"); } @Test public void testGeneratePolicyNumericLong() throws Exception { - final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric("mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "longType"); } - private void generatePolicyNumeric(final String TEST_NAME, + private void generatePolicyNumeric( String mappingFileName, String policyFileName, String extensionPropName) throws Exception { @@ -1196,11 +1160,11 @@ private void generatePolicyNumeric(final String TEST_NAME, new File(MidPointTestConstants.OBJECTS_DIR, policyFileName)); final ValuePolicyType valuePolicyType = valuePolicy.asObjectable(); // GIVEN - PrismContext prismContext = evaluator.getPrismContext(); - MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMappingBuilder(mappingFileName, - TEST_NAME, valuePolicyType, ItemPath.create( - UserType.F_EXTENSION, - new QName(NS_EXTENSION, extensionPropName)), null) + MappingImpl, PrismPropertyDefinition> mapping = + evaluator.createMappingBuilder( + mappingFileName, getTestNameShort(), valuePolicyType, + ItemPath.create(UserType.F_EXTENSION, new QName(NS_EXTENSION, extensionPropName)), + null) .build(); OperationResult opResult = new OperationResult(contextName()); @@ -1222,10 +1186,9 @@ private void generatePolicyNumeric(final String TEST_NAME, // GIVEN (2) - mapping = evaluator.createMappingBuilder(mappingFileName, - TEST_NAME, valuePolicyType, ItemPath.create( - UserType.F_EXTENSION, - new QName(NS_EXTENSION, extensionPropName)), null) + mapping = evaluator.createMappingBuilder( + mappingFileName, getTestNameShort(), valuePolicyType, + ItemPath.create(UserType.F_EXTENSION, new QName(NS_EXTENSION, extensionPropName)), null) .build(); // WHEN (2) @@ -1251,7 +1214,7 @@ public void testGenerateProtectedString() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-generate.xml", shortTestName, SchemaConstants.PATH_PASSWORD_VALUE, null); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -1263,7 +1226,7 @@ public void testGenerateProtectedString() throws Exception { PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); - System.out.println("Generated excrypted value: " + value1); + System.out.println("Generated encrypted value: " + value1); assertNotNull(value1); assertNotNull(value1.getEncryptedDataType()); } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java index 0d2d1ca8caf..3670441d781 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java @@ -46,8 +46,6 @@ */ public class TestMappingDynamicSysVar extends AbstractModelCommonTest { - private static final Trace LOGGER = TraceManager.getTrace(TestMappingDynamicSysVar.class); - private MappingTestEvaluator evaluator; @BeforeClass @@ -73,14 +71,11 @@ public void testScriptSystemVariablesConditionAddObjectTrue(String filename) thr user.asObjectable().getEmployeeType().add("CAPTAIN"); ObjectDelta delta = DeltaFactory.Object.createAddDelta(user); - String shortTestName = getTestNameShort(); - MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, shortTestName, "title", delta); - - OperationResult opResult = new OperationResult(shortTestName); + MappingImpl, PrismPropertyDefinition> mapping = + evaluator.createMapping(filename, getTestNameShort(), "title", delta); // WHEN - mapping.evaluate(createTask(), opResult); + mapping.evaluate(createTask(), createOperationResult()); // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -567,7 +562,7 @@ public void testPathEnum() throws Exception { // WHEN System.out.println("WHEN"); - LOGGER.info("WHEN"); + logger.info("WHEN"); mapping.evaluate(createTask(), opResult); // THEN @@ -584,7 +579,7 @@ public void testEmployeeNumberString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberString", + getTestNameShort(), "employeeType", // target "employeeNumber", // changed property "666"); // changed values @@ -598,11 +593,10 @@ public void testEmployeeNumberString() throws Exception { @Test public void testEmployeeNumberPolyString() throws Exception { // WHEN - String shortTestName = getTestNameShort(); PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - shortTestName, + getTestNameShort(), "additionalName", // target "employeeNumber", // changed property "666"); // changed values @@ -623,7 +617,7 @@ public void testEmployeeNumberInt() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberString", + getTestNameShort(), UserType.F_EXTENSION.append(SchemaTestConstants.EXTENSION_INT_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values @@ -639,7 +633,7 @@ public void testEmployeeNumberInteger() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberString", + getTestNameShort(), UserType.F_EXTENSION.append(SchemaTestConstants.EXTENSION_INTEGER_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values @@ -655,7 +649,7 @@ public void testEmployeeNumberLong() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberString", + getTestNameShort(), UserType.F_EXTENSION.append(SchemaTestConstants.EXTENSION_LONG_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values @@ -671,7 +665,7 @@ public void testEmployeeNumberDecimal() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberString", + getTestNameShort(), UserType.F_EXTENSION.append(SchemaTestConstants.EXTENSION_DECIMAL_TYPE_ELEMENT), // target "employeeNumber", // changed property "666.33"); // changed values @@ -687,7 +681,7 @@ public void testEmployeeNumberProtectedString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-employee-number.xml", - "testEmployeeNumberProtectedString", + getTestNameShort(), UserType.F_CREDENTIALS.append(CredentialsType.F_PASSWORD).append(PasswordType.F_VALUE), // target "employeeNumber", // changed property "666"); // changed values @@ -941,7 +935,7 @@ public void testPasswordString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-password.xml", - "testPasswordString", + getTestNameShort(), "employeeType", // target ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values @@ -957,7 +951,7 @@ public void testPasswordPolyString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-password.xml", - "testPasswordPolyString", + getTestNameShort(), UserType.F_ADDITIONAL_NAME.getLocalPart(), // target ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values @@ -973,7 +967,7 @@ public void testPasswordProtectedString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-password.xml", - "testPasswordPolyString", + getTestNameShort(), ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // target ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values @@ -989,7 +983,7 @@ public void testPasswordDecryptString() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicReplace( "mapping-script-system-variables-password-decrypt.xml", - "testPasswordDecryptString", + getTestNameShort(), "employeeType", // target ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java index 2fc67983729..98c100d3505 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java @@ -35,9 +35,7 @@ public void setupFactory() throws SAXException, IOException, SchemaException { public void testValueSingleDeep() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-value-single-deep.xml", - "testValue", - "costCenter"); // target + "mapping-value-single-deep.xml", getTestNameShort(), "costCenter"); // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); @@ -49,9 +47,7 @@ public void testValueSingleDeep() throws Exception { public void testValueSingleShallow() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-value-single-shallow.xml", - "testValue", - "costCenter"); // target + "mapping-value-single-shallow.xml", getTestNameShort(), "costCenter"); // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); @@ -63,9 +59,7 @@ public void testValueSingleShallow() throws Exception { public void testValueMultiDeep() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-value-multi-deep.xml", - "testValueMulti", - "employeeType"); // target + "mapping-value-multi-deep.xml", getTestNameShort(), "employeeType"); // THEN PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); @@ -77,9 +71,7 @@ public void testValueMultiDeep() throws Exception { public void testValueMultiShallow() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-value-multi-shallow.xml", - "testValueMulti", - "employeeType"); // target + "mapping-value-multi-shallow.xml", getTestNameShort(), "employeeType"); // THEN PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); @@ -91,9 +83,7 @@ public void testValueMultiShallow() throws Exception { public void testPathNoSource() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-path-system-variables-nosource.xml", - "testPathNoSource", - "employeeType"); // target + "mapping-path-system-variables-nosource.xml", getTestNameShort(), "employeeType"); // THEN PrismAsserts.assertTripleZero(outputTriple, "jack"); @@ -105,9 +95,7 @@ public void testPathNoSource() throws Exception { public void testConstFoo() throws Exception { // WHEN PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMapping( - "mapping-const-foo.xml", - "testValue", - "costCenter"); // target + "mapping-const-foo.xml", getTestNameShort(), "costCenter"); // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java index 9e46d817f58..6a51f3a0732 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java @@ -34,19 +34,18 @@ import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author lazyman */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) -public class ExpressionHandlerImplTest extends AbstractSpringTest { +public class ExpressionHandlerImplTest extends AbstractSpringTest + implements OperationResultTestMixin { - private static final Trace LOGGER = TraceManager.getTrace(ExpressionHandlerImplTest.class); private static final File TEST_FOLDER = new File("./src/test/resources/expr"); private static final File TEST_FOLDER_COMMON = new File("./src/test/resources/common"); @@ -87,10 +86,10 @@ public void testConfirmUser() throws Exception { + "" + "", ExpressionType.COMPLEX_TYPE); - OperationResult result = new OperationResult("testConfirmUser"); - boolean confirmed = expressionHandler.evaluateConfirmationExpression(user.asObjectable(), account.asObjectable(), expression, - null, result); - LOGGER.info(result.debugDump()); + OperationResult result = createOperationResult(); + boolean confirmed = expressionHandler.evaluateConfirmationExpression( + user.asObjectable(), account.asObjectable(), expression, null, result); + logger.info(result.debugDump()); assertTrue("Wrong expression result (expected true)", confirmed); } @@ -113,11 +112,11 @@ public void testEvaluateExpression() throws Exception { .getEntryAsRoot(new QName(SchemaConstants.NS_C, "expression")); ExpressionType expression = PrismTestUtil.getPrismContext().parserFor(expressionNode).parseRealValue(ExpressionType.class); - LOGGER.debug("Expression: {}", SchemaDebugUtil.prettyPrint(expression)); + logger.debug("Expression: {}", SchemaDebugUtil.prettyPrint(expression)); - OperationResult result = new OperationResult("testCorrelationRule"); + OperationResult result = createOperationResult(); String name = expressionHandler.evaluateExpression(accountType, expression, "test expression", null, result); - LOGGER.info(result.debugDump()); + logger.info(result.debugDump()); assertEquals("Wrong expression result", "hbarbossa", name); } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java index 64381d33186..f9c95e88cf5 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java @@ -98,7 +98,8 @@ public void testHello() throws Exception { assertExecuteScriptExpressionString(null, "Hello swashbuckler"); } - private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws SchemaException, IOException { + private ScriptExpressionEvaluatorType parseScriptType(String fileName) + throws SchemaException, IOException { ScriptExpressionEvaluatorType expressionType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE); return expressionType; @@ -106,11 +107,9 @@ private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws Sc @Test public void testGetUserByOid() throws Exception { - final String TEST_NAME = "testGetUserByOid"; - // GIVEN - OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME); - PrismObject chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result); + PrismObject chef = repositoryService.getObject( + UserType.class, CHEF_OID, null, getTestOperationResult()); ExpressionVariables variables = createVariables(ExpressionConstants.VAR_USER, chef, chef.getDefinition()); @@ -122,7 +121,7 @@ public void testGetUserByOid() throws Exception { public void testGetManagersOids() throws Exception { // GIVEN Task task = getTestTask(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); String shortTestName = getTestNameShort(); PrismObject chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result); @@ -148,7 +147,8 @@ public void testGetManagersOids() throws Exception { oids.add(scriptOutputs.get(0).getValue()); oids.add(scriptOutputs.get(1).getValue()); oids.add(scriptOutputs.get(2).getValue()); - Set expectedOids = new HashSet<>(Arrays.asList(new String[] { CHEESE_OID, CHEESE_JR_OID, LECHUCK_OID })); + Set expectedOids = new HashSet<>( + Arrays.asList(CHEESE_OID, CHEESE_JR_OID, LECHUCK_OID)); assertEquals("Unexpected script output", expectedOids, oids); } @@ -157,25 +157,24 @@ public void testGetManagersOids() throws Exception { */ @Test public void testIsUniquePropertyValue() throws Exception { - final String TEST_NAME = "testIsUniquePropertyValue"; - // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); - OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); + String testName = getTestNameShort(); PrismObject chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result); - ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + TEST_NAME + ".xml"); + ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + testName + ".xml"); PrismPropertyDefinition outputDefinition = getPrismContext().definitionFactory().createPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_BOOLEAN); ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, - MiscSchemaUtil.getExpressionProfile(), expressionFactory, TEST_NAME, task, result); + MiscSchemaUtil.getExpressionProfile(), expressionFactory, testName, task, result); ExpressionVariables variables = createVariables( ExpressionConstants.VAR_USER, chef, chef.getDefinition(), ExpressionConstants.VAR_VALUE, "Scumm Bar Chef", String.class); // WHEN - List> scriptOutputs = evaluate(scriptExpression, variables, false, TEST_NAME, null, result); + List> scriptOutputs = evaluate(scriptExpression, variables, false, testName, null, result); // THEN display("Script output", scriptOutputs); @@ -186,14 +185,11 @@ public void testIsUniquePropertyValue() throws Exception { @Test public void testGetOrgByName() throws Exception { - final String TEST_NAME = "testGetOrgByName"; assertExecuteScriptExpressionString(null, F0006_OID); } @Test public void testGetLinkedShadowName() throws Exception { - final String TEST_NAME = "testGetLinkedShadowName"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -207,8 +203,6 @@ public void testGetLinkedShadowName() throws Exception { @Test public void testGetLinkedShadowKindIntentUsername() throws Exception { - final String TEST_NAME = "testGetLinkedShadowKindIntentUsername"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -222,8 +216,6 @@ public void testGetLinkedShadowKindIntentUsername() throws Exception { @Test public void testGetLinkedShadowKindIntentFullname() throws Exception { - final String TEST_NAME = "testGetLinkedShadowKindIntentFullname"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -237,8 +229,6 @@ public void testGetLinkedShadowKindIntentFullname() throws Exception { @Test public void testGetLinkedShadowNameRepo() throws Exception { - final String TEST_NAME = "testGetLinkedShadowNameRepo"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -252,8 +242,6 @@ public void testGetLinkedShadowNameRepo() throws Exception { @Test public void testGetLinkedShadowKindIntentUsernameRepo() throws Exception { - final String TEST_NAME = "testGetLinkedShadowKindIntentUsernameRepo"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -267,8 +255,6 @@ public void testGetLinkedShadowKindIntentUsernameRepo() throws Exception { @Test public void testGetLinkedShadowKindIntentFullnameRepo() throws Exception { - final String TEST_NAME = "testGetLinkedShadowKindIntentFullnameRepo"; - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject user = getUser(USER_GUYBRUSH_OID); @@ -293,7 +279,7 @@ private String executeScriptExpressionString(ExpressionVariables variables) ObjectNotFoundException, CommunicationException, ConfigurationException, IOException { // GIVEN Task task = createPlainTask("executeScriptExpressionString"); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); String shortTestName = getTestNameShort(); ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + shortTestName + ".xml"); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java index b4fbc6ba597..439108cd638 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java @@ -688,9 +688,6 @@ private AssignmentType createRoleAssignmentDisabled(TestResource role) { // */ // @Test // public void test150UnassignOrganizerFromAdam() throws Exception { -// final String TEST_NAME = "test150UnassignOrganizerFromAdam"; -// TestUtil.displayTestTitle(this, TEST_NAME); -// // // GIVEN // Task task = createTask(TestAssignedMappings.class.getName() + "." + TEST_NAME); // setModelLoggingTracing(task); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java index 07aae4b0647..78a284f1e51 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java @@ -163,7 +163,7 @@ public void test020AssignAccountToJackSync() throws Exception { assertFalse("No contexts recorded by the hook", hookContexts.isEmpty()); } finally { - displayCleanup(TEST_NAME); + displayCleanup(); mockClockworkHook.reset(); unassignJackAccount(); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); @@ -178,7 +178,7 @@ public void test030AssignAccountToJackAsyncNoserialize() throws Exception { assignAccountToJackAsync(TEST_NAME, false); } finally { - displayCleanup(TEST_NAME); + displayCleanup(); mockClockworkHook.reset(); unassignJackAccount(); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); @@ -193,7 +193,7 @@ public void test031AssignAccountToJackAsyncSerialize() throws Exception { assignAccountToJackAsync(TEST_NAME, true); } finally { - displayCleanup(TEST_NAME); + displayCleanup(); mockClockworkHook.reset(); unassignJackAccount(); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicy.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicy.java index 402fdb0f9a6..0cfc6e870e5 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicy.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicy.java @@ -31,8 +31,6 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType; import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -44,8 +42,6 @@ public class TestPasswordPolicy extends AbstractInternalModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/lens/ppolicy/"); - private static final Trace LOGGER = TraceManager.getTrace(TestPasswordPolicy.class); - private static final String USER_AB_USERNAME = "ab"; private static final String USER_AB_FULL_NAME = "Ad Fel"; private static final String USER_AB_GIVEN_NAME = "Ad"; @@ -112,7 +108,7 @@ public void testPasswordGeneratorComplexNegative() throws Exception { for (StringLimitType l : pp.getStringPolicy().getLimitations().getLimit()) { l.setMustBeFirst(true); } - LOGGER.info("Negative testing: passwordGeneratorComplexTest"); + logger.info("Negative testing: passwordGeneratorComplexTest"); try { valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, false, null, getTestNameShort(), task, result); assertNotReached(); @@ -190,7 +186,7 @@ public void testValueGenerateEmpty() throws Exception { OperationResult result = task.getResult(); File file = new File(TEST_DIR, "value-policy-generate-empty.xml"); - LOGGER.info("Positive testing {}: {}", "testValueGenerate", "value-policy-generate-empty.xml"); + logger.info("Positive testing {}: {}", "testValueGenerate", "value-policy-generate-empty.xml"); ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable(); // WHEN @@ -213,31 +209,31 @@ public void passwordGeneratorTest(String policyFilename) OperationResult result = task.getResult(); File file = new File(TEST_DIR, policyFilename); - LOGGER.info("Positive testing {}: {}", getTestNameShort(), policyFilename); + logger.info("Positive testing {}: {}", getTestNameShort(), policyFilename); ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable(); String psswd; // generate minimal size passwd for (int i = 0; i < 100; i++) { psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, true, null, getTestNameShort(), task, result); - LOGGER.info("Generated password:" + psswd); + logger.info("Generated password:" + psswd); result.computeStatus(); if (!result.isSuccess()) { - LOGGER.info("Result:" + result.debugDump()); + logger.info("Result:" + result.debugDump()); AssertJUnit.fail("Password generator failed:\n" + result.debugDump()); } assertNotNull(psswd); assertPassword(psswd, pp); } // genereata to meet as possible - LOGGER.info("-------------------------"); + logger.info("-------------------------"); // Generate up to possible for (int i = 0; i < 100; i++) { psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp, 10, false, null, getTestNameShort(), task, result); - LOGGER.info("Generated password:" + psswd); + logger.info("Generated password:" + psswd); result.computeStatus(); if (!result.isSuccess()) { - LOGGER.info("Result:" + result.debugDump()); + logger.info("Result:" + result.debugDump()); } AssertJUnit.assertTrue(result.isSuccess()); assertNotNull(psswd); @@ -373,8 +369,8 @@ private boolean pwdValidHelper(String password, ValuePolicyType pp) throws Schem result.computeStatus(); String msg = "-> Policy " + pp.getName() + ", password '" + password + "': " + result.getStatus(); System.out.println(msg); - LOGGER.info(msg); - LOGGER.trace(result.debugDump()); + logger.info(msg); + logger.trace(result.debugDump()); return (result.isSuccess()); } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java index b3961d9f706..57cf7c7c597 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java @@ -51,7 +51,7 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception{ final String TEST_NAME = "text001testReconcileScriptsWhenProvisioning"; Task task = taskManager.createTaskInstance(TEST_NAME); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); ObjectDelta delta = createModifyUserAddAccount(USER_JACK_OID, getDummyResourceObject()); Collection> deltas = new ArrayList<>(); @@ -124,7 +124,7 @@ public void test003testReconcileScriptsAddUserAction() throws Exception{ final String TEST_NAME = "test003testReconcileScriptsAddUserAction"; Task task = taskManager.createTaskInstance(TEST_NAME); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); ShadowType shadow = parseObjectType(new File(ACCOUNT_BEFORE_SCRIPT_FILENAME), ShadowType.class); @@ -169,7 +169,7 @@ public void test005TestDryRunDelete() throws Exception{ final String TEST_NAME = "test005TestDryRunDelete"; PrismObject task = getTask(TASK_RECON_DUMMY_OID); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); PropertyDelta dryRunDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(PATH_MODEL_EXTENSION_DRY_RUN, task.getDefinition(), true); Collection modifications = new ArrayList<>(); @@ -200,7 +200,7 @@ public void test006TestReconDelete() throws Exception{ final String TEST_NAME = "test006TestReconDelete"; PrismObject task = getTask(TASK_RECON_DUMMY_OID); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); PropertyDelta dryRunDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( PATH_MODEL_EXTENSION_DRY_RUN, task.getDefinition(), false); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java index facdb4b6c49..935df7efd90 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java @@ -11,7 +11,7 @@ import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.AbstractSpringTest; -import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; @@ -32,10 +32,7 @@ import static org.testng.AssertJUnit.*; -/** - * @author semancik - * - */ +@UnusedTestElement("reason unknown, but it FAILS") @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestMigrator extends AbstractSpringTest { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java index 967ff147547..c6039f2927b 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java @@ -18,7 +18,7 @@ import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -41,10 +41,7 @@ import static org.apache.commons.collections.CollectionUtils.addIgnoreNull; import static org.testng.AssertJUnit.*; -/** - * @author mederly - * - */ +@UnusedTestElement("reason unknown, 2 tests FAIL") @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestVisualizer extends AbstractInternalModelIntegrationTest { @@ -55,9 +52,6 @@ public class TestVisualizer extends AbstractInternalModelIntegrationTest { @Autowired private PrismContext prismContext; - @Autowired - private TaskManager taskManager; - @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -66,7 +60,6 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void test100UserBasic() throws Exception { - final String TEST_NAME = "test100UserBasic"; Task task = getTestTask(); PrismObject u = prismContext.createObject(UserType.class); @@ -87,7 +80,6 @@ public void test100UserBasic() throws Exception { @Test public void test110UserWithContainers() throws Exception { - final String TEST_NAME = "test101UserWithContainers"; Task task = getTestTask(); PrismObject u = prismContext.createObject(UserType.class); @@ -125,7 +117,6 @@ public void test110UserWithContainers() throws Exception { @Test public void test200UserDeltaBasic() throws Exception { - final String TEST_NAME = "test200UserDeltaBasic"; Task task = getTestTask(); ObjectDelta delta = deltaFor(UserType.class) @@ -145,7 +136,6 @@ public void test200UserDeltaBasic() throws Exception { @Test public void test210UserDeltaContainers() throws Exception { - final String TEST_NAME = "test210UserDeltaContainers"; Task task = getTestTask(); AssignmentType ass1 = new AssignmentType(prismContext); @@ -175,7 +165,6 @@ public void test210UserDeltaContainers() throws Exception { @Test public void test212UserDeltaContainerSimple() throws Exception { - final String TEST_NAME = "test212UserDeltaContainerSimple"; Task task = getTestTask(); ObjectDelta delta = deltaFor(UserType.class) @@ -196,7 +185,6 @@ public void test212UserDeltaContainerSimple() throws Exception { @Test public void test220UserContainerReplace() throws Exception { - final String TEST_NAME = "test220UserContainerReplace"; Task task = getTestTask(); AssignmentType ass1 = new AssignmentType(prismContext); @@ -227,7 +215,6 @@ public void test220UserContainerReplace() throws Exception { @Test public void test230UserContainerDelete() throws Exception { - final String TEST_NAME = "test230UserContainerDelete"; Task task = getTestTask(); AssignmentType ass1 = new AssignmentType(prismContext); @@ -254,7 +241,6 @@ public void test230UserContainerDelete() throws Exception { @Test public void test300UserAssignmentPreview() throws Exception { - final String TEST_NAME = "test300UserAssignmentPreview"; Task task = getTestTask(); PrismObject jack = getUser(USER_JACK_OID); @@ -272,7 +258,7 @@ public void test300UserAssignmentPreview() throws Exception { /// WHEN when(); - ModelContext modelContext = modelInteractionService.previewChanges(Collections.>singletonList(delta), null, task, task.getResult()); + ModelContext modelContext = modelInteractionService.previewChanges(Collections.singletonList(delta), null, task, task.getResult()); List> primaryDeltas = new ArrayList<>(); List> secondaryDeltas = new ArrayList<>(); fillDeltas(modelContext, primaryDeltas, secondaryDeltas); @@ -290,7 +276,6 @@ public void test300UserAssignmentPreview() throws Exception { @Test public void test305UserAssignmentAdd() throws Exception { - final String TEST_NAME = "test305UserAssignmentAdd"; Task task = getTestTask(); display("jack", getUser(USER_JACK_OID)); @@ -307,7 +292,7 @@ public void test305UserAssignmentAdd() throws Exception { when(); final Scene scene = visualizer.visualizeDelta(delta, task, task.getResult()); - modelService.executeChanges(Collections.>singletonList(delta), null, task, task.getResult()); + modelService.executeChanges(Collections.singletonList(delta), null, task, task.getResult()); // THEN then(); @@ -319,7 +304,6 @@ public void test305UserAssignmentAdd() throws Exception { @Test public void test307UserDisablePreview() throws Exception { - final String TEST_NAME = "test307UserDisablePreview"; Task task = getTestTask(); ObjectDelta delta = deltaFor(UserType.class) @@ -328,7 +312,7 @@ public void test307UserDisablePreview() throws Exception { /// WHEN when(); - ModelContext modelContext = modelInteractionService.previewChanges(Collections.>singletonList(delta), null, task, task.getResult()); + ModelContext modelContext = modelInteractionService.previewChanges(Collections.singletonList(delta), null, task, task.getResult()); List> primaryDeltas = new ArrayList<>(); List> secondaryDeltas = new ArrayList<>(); fillDeltas(modelContext, primaryDeltas, secondaryDeltas); @@ -364,7 +348,6 @@ protected void fillDeltas(ModelContext modelContext, List delta = deltaFor(UserType.class) @@ -408,7 +390,6 @@ public void test320UserLinkRefAdd() throws Exception { @Test public void test330UserLinkRefReplaceNoOp() throws Exception { - final String TEST_NAME = "test330UserLinkRefReplaceNoOp"; Task task = getTestTask(); ObjectDelta delta = deltaFor(UserType.class) @@ -428,7 +409,6 @@ public void test330UserLinkRefReplaceNoOp() throws Exception { @Test public void test340UserLinkRefReplaceOp() throws Exception { - final String TEST_NAME = "test340UserLinkRefReplaceOp"; Task task = getTestTask(); ObjectDelta delta = deltaFor(UserType.class) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java index 222b2c92c08..4b7b051a925 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java @@ -638,7 +638,7 @@ protected void assertPasswordMetadata(PrismObject user, boolean create @SuppressWarnings({ "rawtypes", "unchecked" }) protected void clearUserOrgAndRoleRefs(String userOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - OperationResult result = new OperationResult("clearUserOrgAndRoleRefs"); + OperationResult result = createOperationResult("clearUserOrgAndRoleRefs"); Collection modifications = new ArrayList<>(); ReferenceDelta parentOrgRefDelta = prismContext.deltaFactory().reference().createModificationReplace( UserType.F_PARENT_ORG_REF, getUserDefinition(), (PrismReferenceValue)null); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java index b54e6769631..f02eec31ac8 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java @@ -18,6 +18,7 @@ import com.evolveum.midpoint.model.impl.importer.ImportAccountsFromResourceTaskHandler; import com.evolveum.midpoint.prism.query.OrgFilter; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.beans.factory.annotation.Autowired; @@ -45,8 +46,6 @@ import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import javax.xml.datatype.XMLGregorianCalendar; @@ -59,8 +58,6 @@ public class AbstractInitializedModelIntegrationTest extends AbstractConfiguredM private static final int NUM_FUNCTIONAL_ORGS = 6; private static final int NUM_PROJECT_ORGS = 3; - protected static final Trace LOGGER = TraceManager.getTrace(AbstractInitializedModelIntegrationTest.class); - private static final int NUMBER_OF_IMPORTED_USERS = 5; private static final int NUMBER_OF_IMPORTED_ROLES = 15; @@ -109,7 +106,7 @@ public AbstractInitializedModelIntegrationTest() { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); assumeConflictResolutionAction(getDefaultConflictResolutionAction()); @@ -292,6 +289,7 @@ protected File getResourceDummyBlueFile() { return RESOURCE_DUMMY_BLUE_FILE; } + @UnusedTestElement protected File getResourceDummyGreenFile() { return RESOURCE_DUMMY_GREEN_FILE; } @@ -430,6 +428,6 @@ protected void assertShadowOperationalData(PrismObject shadow, Synch } protected Collection getCheckingProgressListenerCollection() { - return Collections.singleton((ProgressListener)checkingProgressListener); + return Collections.singleton(checkingProgressListener); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java index 2c542850a86..2f545b3abb1 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java @@ -10,61 +10,54 @@ import static org.testng.AssertJUnit.assertTrue; import java.io.File; -import java.util.*; import java.util.Objects; +import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; - import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.midpoint.audit.api.AuditEventStage; -import com.evolveum.midpoint.audit.api.AuditEventType; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.xml.XmlTypeConverter; -import com.evolveum.midpoint.schema.ObjectDeltaOperation; -import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.evolveum.midpoint.audit.api.AuditEventRecord; +import com.evolveum.midpoint.audit.api.AuditEventStage; +import com.evolveum.midpoint.audit.api.AuditEventType; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.prism.xml.XmlTypeConverter; +import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * Test of Model Audit Service. - * + *

* Two users, interlaced events: jack and herman. - * + *

* Jack already exists, but there is no create audit record for him. This simulates trimmed * audit log. There are several fresh modify operations. - * + *

* Herman is properly created and modified. We have all the audit records. - * + *

* The tests check if audit records are created and that they can be listed. * The other tests check that the state can be reconstructed by the time machine (object history). * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAudit extends AbstractInitializedModelIntegrationTest { @@ -94,11 +87,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); } - @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - assertTrue(modelAuditService.supportsRetrieval()); Task task = getTestTask(); @@ -116,8 +106,6 @@ public void test000Sanity() throws Exception { @Test public void test010SanityJack() throws Exception { - final String TEST_NAME = "test010SanityJack"; - // WHEN List auditRecords = getObjectAuditRecords(USER_JACK_OID); @@ -129,8 +117,6 @@ public void test010SanityJack() throws Exception { @Test public void test100ModifyUserJackKid() throws Exception { - final String TEST_NAME = "test100ModifyUserJackKid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -157,8 +143,6 @@ public void test100ModifyUserJackKid() throws Exception { */ @Test public void test105CreateUserHerman() throws Exception { - final String TEST_NAME = "test105CreateUserHerman"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -188,12 +172,9 @@ public void test105CreateUserHerman() throws Exception { @Test public void test110ModifyUserJackSailor() throws Exception { - final String TEST_NAME = "test110ModifyUserJackSailor"; - Task task = getTestTask(); OperationResult result = task.getResult(); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_TITLE, createPolyString("Sailor")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Hermit on Monkey Island"); @@ -220,8 +201,6 @@ public void test110ModifyUserJackSailor() throws Exception { @Test public void test115ModifyUserHermanMarooned() throws Exception { - final String TEST_NAME = "test115ModifyUserHermanMarooned"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -247,11 +226,8 @@ public void test115ModifyUserHermanMarooned() throws Exception { assertRecordsFromInitial(hermanMaroonedTs, 8); } - @Test public void test120ModifyUserJackCaptain() throws Exception { - final String TEST_NAME = "test120ModifyUserJackCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -280,8 +256,6 @@ public void test120ModifyUserJackCaptain() throws Exception { @Test public void test125ModifyUserHermanHermit() throws Exception { - final String TEST_NAME = "test125ModifyUserHermanHermit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -301,7 +275,6 @@ public void test125ModifyUserHermanHermit() throws Exception { modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - // THEN then(); assertSuccess(result); @@ -316,8 +289,6 @@ public void test125ModifyUserHermanHermit() throws Exception { @Test public void test135ModifyUserHermanCivilisedHermit() throws Exception { - final String TEST_NAME = "test135ModifyUserHermanCivilisedHermit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -332,7 +303,6 @@ public void test135ModifyUserHermanCivilisedHermit() throws Exception { modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - // THEN then(); assertSuccess(result); @@ -347,8 +317,6 @@ public void test135ModifyUserHermanCivilisedHermit() throws Exception { @Test public void test200ReconstructJackSailor() throws Exception { - final String TEST_NAME = "test200ReconstructJackSailor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -377,8 +345,6 @@ public void test200ReconstructJackSailor() throws Exception { @Test public void test210ReconstructJackKid() throws Exception { - final String TEST_NAME = "test210ReconstructJackKid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -409,8 +375,6 @@ public void test210ReconstructJackKid() throws Exception { */ @Test public void test250ReconstructHermanCreated() throws Exception { - final String TEST_NAME = "test250ReconstructHermanCreated"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -448,8 +412,6 @@ public void test250ReconstructHermanCreated() throws Exception { */ @Test public void test252ReconstructHermanMarooned() throws Exception { - final String TEST_NAME = "test252ReconstructHermanMarooned"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -480,8 +442,6 @@ public void test252ReconstructHermanMarooned() throws Exception { */ @Test public void test254ReconstructHermanHermit() throws Exception { - final String TEST_NAME = "test254ReconstructHermanHermit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -510,8 +470,6 @@ public void test254ReconstructHermanHermit() throws Exception { @Test public void test300QueryUnknown() throws Exception { - final String TEST_NAME = "test300QueryUnknown"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -564,13 +522,12 @@ private void assertRecordsFromInitial(XMLGregorianCalendar to, int expectedNumbe */ @Test public void test300ConcurrentAudits() throws Exception { - final String TEST_NAME = "test300ConcurrentAudits"; final int NUM_THREADS = 2; final int ITERATIONS = 300; final long TIMEOUT = 600000; if (isH2()) { - display("Skipping " + TEST_NAME + " because of H2 database"); + display("Skipping " + getTestNameShort() + " because of H2 database"); return; } @@ -604,7 +561,7 @@ public void test300ConcurrentAudits() throws Exception { results.set(index, null); } catch (Throwable t) { System.err.println("Thread " + index + " got an exception " + t); - LoggingUtils.logUnexpectedException(LOGGER, "Thread {} got an exception", t, index); + LoggingUtils.logUnexpectedException(logger, "Thread {} got an exception", t, index); results.set(index, t); } }); @@ -643,13 +600,12 @@ public void test300ConcurrentAudits() throws Exception { */ @Test public void test310ConcurrentAuditsRaw() throws Exception { - final String TEST_NAME = "test310ConcurrentAuditsRaw"; final int NUM_THREADS = 2; final int ITERATIONS = 300; final long TIMEOUT = 600000; if (isH2()) { - display("Skipping " + TEST_NAME + " because of H2 database"); + display("Skipping " + getTestNameShort() + " because of H2 database"); return; } @@ -669,7 +625,7 @@ public void test310ConcurrentAuditsRaw() throws Exception { display("Executing iteration " + iteration + " in worker " + index); AuditEventRecord record = new AuditEventRecord(AuditEventType.MODIFY_OBJECT, AuditEventStage.EXECUTION); record.setEventIdentifier( - String.valueOf(iteration + ":" + System.currentTimeMillis()) + "-" + (int) (Math.random() * 1000000)); + iteration + ":" + System.currentTimeMillis() + "-" + (int) (Math.random() * 1_000_000)); ObjectDelta delta = prismContext.deltaFor(UserType.class) .item(UserType.F_FULL_NAME).replace(PolyString.fromOrig("Hi" + iteration)) .item(UserType.F_METADATA, MetadataType.F_MODIFY_TIMESTAMP).replace(XmlTypeConverter.createXMLGregorianCalendar(new Date())) @@ -684,7 +640,7 @@ public void test310ConcurrentAuditsRaw() throws Exception { results.set(index, null); } catch (Throwable t) { System.err.println("Thread " + index + " got an exception " + t); - LoggingUtils.logUnexpectedException(LOGGER, "Thread {} got an exception", t, index); + LoggingUtils.logUnexpectedException(logger, "Thread {} got an exception", t, index); results.set(index, t); failed.set(true); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java index 970a2a46bbd..b8d9c970da0 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java @@ -6,10 +6,7 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.List; @@ -30,13 +27,7 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.FailableRunnable; import com.evolveum.midpoint.util.Holder; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -44,14 +35,12 @@ * Test behavior of connectors that have several instances (poolable connectors). * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestConnectorMultiInstance extends AbstractConfiguredModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/multi"); - private static final Trace LOGGER = TraceManager.getTrace(TestConnectorMultiInstance.class); protected DummyResource dummyResourceYellow; protected DummyResourceContoller dummyResourceCtlYellow; @@ -61,7 +50,6 @@ public class TestConnectorMultiInstance extends AbstractConfiguredModelIntegrati private String initialConnectorToString; private String accountGuybrushBlackOid; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -81,8 +69,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - // GIVEN Task task = getTestTask(); @@ -98,8 +84,6 @@ public void test000Sanity() throws Exception { @Test public void test100JackAssignDummyYellow() throws Exception { - final String TEST_NAME = "test100JackAssignDummyYellow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -129,8 +113,6 @@ public void test100JackAssignDummyYellow() throws Exception { */ @Test public void test102ReadJackDummyYellowAgain() throws Exception { - final String TEST_NAME = "test102ReadJackDummyYellowAgain"; - // WHEN PrismObject shadowYellow = getShadowModel(accountJackYellowOid); @@ -151,17 +133,15 @@ public void test102ReadJackDummyYellowAgain() throws Exception { */ @Test public void test110ReadJackDummyYellowBlocking() throws Exception { - final String TEST_NAME = "test110ReadJackDummyYellowBlocking"; - dummyResourceYellow.setBlockOperations(true); final Holder> shadowHolder = new Holder<>(); // WHEN Thread t = executeInNewThread("get1", () -> { - PrismObject shadow = getShadowModel(accountJackYellowOid); - LOGGER.trace("Got shadow {}", shadow); - shadowHolder.setValue(shadow); - }); + PrismObject shadow = getShadowModel(accountJackYellowOid); + logger.trace("Got shadow {}", shadow); + shadowHolder.setValue(shadow); + }); // Give the new thread a chance to get blocked Thread.sleep(200); @@ -194,19 +174,17 @@ public void test110ReadJackDummyYellowBlocking() throws Exception { * for the second operation and that it goes smoothly. */ @Test - public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exception { - final String TEST_NAME = "test120ReadJackDummyYellowTwoOperationsOneBlocking"; - + public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exception { dummyResourceYellow.setBlockOperations(true); final Holder> shadowHolder1 = new Holder<>(); final Holder> shadowHolder2 = new Holder<>(); // WHEN Thread t1 = executeInNewThread("get1", () -> { - PrismObject shadow = getShadowModel(accountJackYellowOid); - LOGGER.trace("Got shadow {}", shadow); - shadowHolder1.setValue(shadow); - }); + PrismObject shadow = getShadowModel(accountJackYellowOid); + logger.trace("Got shadow {}", shadow); + shadowHolder1.setValue(shadow); + }); // Give the new thread a chance to get blocked Thread.sleep(200); @@ -214,16 +192,15 @@ public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exceptio assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 0); assertNull("Unexpected shadow 1", shadowHolder1.getValue()); - dummyResourceYellow.setBlockOperations(false); // This should not be blocked and it should proceed immediately Thread t2 = executeInNewThread("get2", () -> { - PrismObject shadow = getShadowModel(accountJackYellowOid); - LOGGER.trace("Got shadow {}", shadow); - shadowHolder2.setValue(shadow); - }); + PrismObject shadow = getShadowModel(accountJackYellowOid); + logger.trace("Got shadow {}", shadow); + shadowHolder2.setValue(shadow); + }); t2.join(1000); @@ -237,49 +214,47 @@ public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exceptio // THEN - PrismObject shadowYellow1 = shadowHolder1.getValue(); - assertNotNull("No shadow 1", shadowHolder1.getValue()); - display("Shadow yellow 1", shadowYellow1); + PrismObject shadowYellow1 = shadowHolder1.getValue(); + assertNotNull("No shadow 1", shadowHolder1.getValue()); + display("Shadow yellow 1", shadowYellow1); - PrismObject shadowYellow2 = shadowHolder2.getValue(); - assertNotNull("No shadow 2", shadowHolder2.getValue()); - display("Shadow yellow 2", shadowYellow2); + PrismObject shadowYellow2 = shadowHolder2.getValue(); + assertNotNull("No shadow 2", shadowHolder2.getValue()); + display("Shadow yellow 2", shadowYellow2); - assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); - assertConnectorToString(shadowYellow1, dummyResourceCtlYellow, initialConnectorToString); - assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); + assertConnectorToString(shadowYellow1, dummyResourceCtlYellow, initialConnectorToString); + assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); - assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, initialConnectorToString); - assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); + assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, initialConnectorToString); + assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); - assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } /** * Block two read operations. Make sure that new connector instance is created. */ @Test - public void test125ReadJackDummyYellowTwoBlocking() throws Exception { - final String TEST_NAME = "test125ReadJackDummyYellowTwoBlocking"; - + public void test125ReadJackDummyYellowTwoBlocking() throws Exception { dummyResourceYellow.setBlockOperations(true); final Holder> shadowHolder1 = new Holder<>(); final Holder> shadowHolder2 = new Holder<>(); // WHEN Thread t1 = executeInNewThread("get1", () -> { - PrismObject shadow = getShadowModel(accountJackYellowOid); - LOGGER.trace("Got shadow {}", shadow); - shadowHolder1.setValue(shadow); - }); + PrismObject shadow = getShadowModel(accountJackYellowOid); + logger.trace("Got shadow {}", shadow); + shadowHolder1.setValue(shadow); + }); Thread t2 = executeInNewThread("get2", new FailableRunnable() { @Override public void run() throws Exception { - PrismObject shadow = getShadowModel(accountJackYellowOid); - LOGGER.trace("Got shadow {}", shadow); - shadowHolder2.setValue(shadow); + PrismObject shadow = getShadowModel(accountJackYellowOid); + logger.trace("Got shadow {}", shadow); + shadowHolder2.setValue(shadow); } }); @@ -298,28 +273,26 @@ public void run() throws Exception { // THEN dummyResourceYellow.setBlockOperations(false); - PrismObject shadowYellow1 = shadowHolder1.getValue(); - assertNotNull("No shadow 1", shadowHolder1.getValue()); - display("Shadow yellow 1", shadowYellow1); + PrismObject shadowYellow1 = shadowHolder1.getValue(); + assertNotNull("No shadow 1", shadowHolder1.getValue()); + display("Shadow yellow 1", shadowYellow1); - PrismObject shadowYellow2 = shadowHolder2.getValue(); - assertNotNull("No shadow 2", shadowHolder2.getValue()); - display("Shadow yellow 2", shadowYellow2); + PrismObject shadowYellow2 = shadowHolder2.getValue(); + assertNotNull("No shadow 2", shadowHolder2.getValue()); + display("Shadow yellow 2", shadowYellow2); - assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); - assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, getConnectorToString(shadowYellow1, dummyResourceCtlYellow)); + assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, getConnectorToString(shadowYellow1, dummyResourceCtlYellow)); - assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); - assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); + assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); + assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); - assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } @Test public void test200GuybrushAssignDummyBlack() throws Exception { - final String TEST_NAME = "test200GuybrushAssignDummyBlack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -349,13 +322,13 @@ public void test200GuybrushAssignDummyBlack() throws Exception { private Thread executeInNewThread(final String threadName, final FailableRunnable runnable) { Thread t = new Thread(() -> { - try { - login(userAdministrator); - runnable.run(); - } catch (Throwable e) { - LOGGER.error("Error in {}: {}", threadName, e.getMessage(), e); - } - }); + try { + login(userAdministrator); + runnable.run(); + } catch (Throwable e) { + logger.error("Error in {}: {}", threadName, e.getMessage(), e); + } + }); t.setName(threadName); t.start(); return t; @@ -378,7 +351,7 @@ private void assertConnectorToString(PrismObject shadow, private void assertConnectorToStringDifferent(PrismObject shadow, DummyResourceContoller ctl, String expectedVal) throws SchemaException { String connectorVal = getConnectorToString(shadow, ctl); - assertFalse("Unexpected Connector toString, expected a different value: "+connectorVal, expectedVal.equals(connectorVal)); + assertFalse("Unexpected Connector toString, expected a different value: " + connectorVal, expectedVal.equals(connectorVal)); } private void assertConnectorStaticVal(PrismObject shadow, @@ -391,13 +364,13 @@ private void assertConnectorInstances(String msg, String resourceOid, int expect Task task = taskManager.createTaskInstance(TestConnectorMultiInstance.class.getName() + ".assertConnectorInstances"); OperationResult result = task.getResult(); List opStats = modelInteractionService.getConnectorOperationalStatus(resourceOid, task, result); - display("connector stats "+msg, opStats); + display("connector stats " + msg, opStats); assertConnectorInstances(msg, opStats.get(0), expectedActive, expectedIdle); } private void assertConnectorInstances(String msg, ConnectorOperationalStatus opStats, int expectedActive, int expectedIdle) { - assertEquals(msg+" unexpected number of active connector instances", (Integer)expectedActive, opStats.getPoolStatusNumActive()); - assertEquals(msg+" unexpected number of idle connector instances", (Integer)expectedIdle, opStats.getPoolStatusNumIdle()); + assertEquals(msg + " unexpected number of active connector instances", (Integer) expectedActive, opStats.getPoolStatusNumActive()); + assertEquals(msg + " unexpected number of idle connector instances", (Integer) expectedIdle, opStats.getPoolStatusNumIdle()); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIterativeTasks.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIterativeTasks.java index a795680593f..423f6b846c5 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIterativeTasks.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIterativeTasks.java @@ -6,28 +6,32 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.util.Collection; + +import org.slf4j.LoggerFactory; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.RunningTask; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import java.io.File; -import java.util.Collection; - -import static org.testng.AssertJUnit.assertNotNull; /** * Tests AbstractSearchIterativeTaskHandler and related classes. See e.g. MID-5227. */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@UnusedTestElement("not in suite") +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIterativeTasks extends AbstractInitializedModelIntegrationTest { @@ -53,7 +57,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti private void createUsers(OperationResult result) throws ObjectAlreadyExistsException, SchemaException { for (int i = 0; i < BUCKETS; i++) { for (int j = 0; j < USERS_PER_BUCKET; j++) { - createUser(result, i*10 + j); + createUser(result, i * 10 + j); } } } @@ -70,8 +74,6 @@ private void createUser(OperationResult result, int number) throws ObjectAlready */ @Test public void test100RunBucketsMultithreaded() throws Exception { - final String TEST_NAME = "test100RunBucketsMultithreaded"; - // GIVEN // WHEN @@ -88,10 +90,11 @@ public static void checkLightweightSubtasks(TaskType subtask) { RunningTask parent = instance.taskManager.getLocallyRunningTaskByIdentifier(subtask.getParent()); assertNotNull("no parent running task", parent); Collection subtasks = parent.getLightweightAsynchronousSubtasks(); - LOGGER.info("Subtask: {}, parent: {}, its subtasks: ({}): {}", subtask, parent, subtasks.size(), subtasks); + LoggerFactory.getLogger(TestIterativeTasks.class).info( + "Subtask: {}, parent: {}, its subtasks: ({}): {}", subtask, parent, subtasks.size(), subtasks); if (subtasks.size() > EXPECTED_SUBTASKS) { - AssertJUnit.fail("Exceeded the expected number of subtasks: have " + subtasks.size() + ", expected max: " + EXPECTED_SUBTASKS + ": " + subtasks); + AssertJUnit.fail("Exceeded the expected number of subtasks: have " + subtasks.size() + + ", expected max: " + EXPECTED_SUBTASKS + ": " + subtasks); } } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java index bd8c306af06..65a6d18359a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java @@ -1052,7 +1052,7 @@ public void test129DeleteAccount() throws Exception { @Test - public void test130PreviewModifyUserJackAssignAccount() throws Exception { + public void test130PreviewModifyUserJackAssignAccount() { // GIVEN try{ @@ -1092,7 +1092,7 @@ public void test130PreviewModifyUserJackAssignAccount() throws Exception { dummyAuditService.assertNoRecord(); }catch(Exception ex){ - LOGGER.info("Exception {}", ex.getMessage(), ex); + logger.info("Exception {}", ex.getMessage(), ex); } assertSteadyResources(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java index 0fac7c4f8be..36a4159df6a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java @@ -145,8 +145,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test050GetResourceRaw() throws Exception { - final String TEST_NAME = "test050GetResourceRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -194,8 +192,6 @@ public void test050GetResourceRaw() throws Exception { */ @Test public void test052GetResourceNoFetch() throws Exception { - final String TEST_NAME = "test052GetResourceNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -245,8 +241,6 @@ public void test052GetResourceNoFetch() throws Exception { */ @Test public void test053GetResourceNoFetchAgain() throws Exception { - final String TEST_NAME = "test053GetResourceNoFetchAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +292,6 @@ public void test053GetResourceNoFetchAgain() throws Exception { */ @Test public void test055GetResourceNoFetchReadOnly() throws Exception { - final String TEST_NAME = "test055GetResourceNoFetchReadOnly"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -352,8 +344,6 @@ public void test055GetResourceNoFetchReadOnly() throws Exception { */ @Test public void test100SearchResourcesNoFetch() throws Exception { - final String TEST_NAME = "test100SearchResourcesNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -400,8 +390,6 @@ public void test100SearchResourcesNoFetch() throws Exception { */ @Test public void test102SearchResourcesNoFetchReadOnly() throws Exception { - final String TEST_NAME = "test102SearchResourcesNoFetchReadOnly"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -450,8 +438,6 @@ public void test102SearchResourcesNoFetchReadOnly() throws Exception { */ @Test public void test105SearchResourcesIterativeNoFetch() throws Exception { - final String TEST_NAME = "test105SearchResourcesIterativeNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -501,8 +487,6 @@ public void test105SearchResourcesIterativeNoFetch() throws Exception { */ @Test public void test107SearchResourcesIterativeNoFetchReadOnly() throws Exception { - final String TEST_NAME = "test107SearchResourcesIterativeNoFetchReadOnly"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -551,8 +535,6 @@ public void test107SearchResourcesIterativeNoFetchReadOnly() throws Exception { @Test public void test110GetResourceDummy() throws Exception { - final String TEST_NAME = "test110GetResourceDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -593,8 +575,6 @@ public void test110GetResourceDummy() throws Exception { @Test public void test112GetResourceDummyReadOnly() throws Exception { - final String TEST_NAME = "test112GetResourceDummyReadOnly"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -634,10 +614,8 @@ public void test112GetResourceDummyReadOnly() throws Exception { @Test public void test120SearchResources() throws Exception { - final String TEST_NAME = "test120SearchResources"; - // GIVEN - Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -675,10 +653,8 @@ public void test120SearchResources() throws Exception { @Test public void test125SearchResourcesIterative() throws Exception { - final String TEST_NAME = "test125SearchResourcesIterative"; - // GIVEN - Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -793,10 +769,8 @@ private void assertResource(PrismObject resource, boolean expectSc @Test public void test200GetResourceRawAfterSchema() throws Exception { - final String TEST_NAME = "test200GetResourceRawAfterSchema"; - // GIVEN - Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -822,8 +796,6 @@ public void test200GetResourceRawAfterSchema() throws Exception { */ @Test public void test210GetResourceDummyRed() throws Exception { - final String TEST_NAME = "test210GetResourceDummyRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -857,8 +829,6 @@ public void test210GetResourceDummyRed() throws Exception { @Test public void test750GetResourceRaw() throws Exception { - final String TEST_NAME = "test750GetResourceRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -899,8 +869,6 @@ public void test750GetResourceRaw() throws Exception { @Test public void test752GetResourceDummy() throws Exception { - final String TEST_NAME = "test752GetResourceDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -932,8 +900,6 @@ public void test752GetResourceDummy() throws Exception { @Test public void test760ModifyConfigurationString() throws Exception { - final String TEST_NAME = "test760ModifyConfigurationString"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -958,8 +924,6 @@ public void test760ModifyConfigurationString() throws Exception { @Test public void test761ModifyConfigurationStringRaw() throws Exception { - final String TEST_NAME = "test761ModifyConfigurationStringRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -985,8 +949,7 @@ public void test761ModifyConfigurationStringRaw() throws Exception { @Test public void test765ModifyConfigurationDiffExpressionRawPrismContextParse() throws Exception { - final String TEST_NAME = "test765ModifyConfigurationDiffExpressionRawPrismContextParse"; - modifyConfigurationDiffExpressionRaw(TEST_NAME, xml -> prismContext.parseObject(xml)); + modifyConfigurationDiffExpressionRaw(xml -> prismContext.parseObject(xml)); } /** @@ -994,8 +957,7 @@ public void test765ModifyConfigurationDiffExpressionRawPrismContextParse() throw */ @Test public void test767ModifyConfigurationDiffExpressionRawValidatorParse() throws Exception { - final String TEST_NAME = "test767ModifyConfigurationDiffExpressionRawValidatorParse"; - modifyConfigurationDiffExpressionRaw(TEST_NAME, xml -> { + modifyConfigurationDiffExpressionRaw(xml -> { final Holder> objectHolder = new Holder<>(); EventHandler handler = new EventHandler() { @@ -1019,13 +981,13 @@ public void handleGlobalError(OperationResult currentResult) { LegacyValidator validator = new LegacyValidator(prismContext, handler); validator.setVerbose(true); validator.setValidateSchema(false); - OperationResult result = new OperationResult("validator"); + OperationResult result =createOperationResult("validator"); validator.validateObject(xml, result); return objectHolder.getValue(); }); } - private void modifyConfigurationDiffExpressionRaw(final String TEST_NAME, + private void modifyConfigurationDiffExpressionRaw( FailableFunction> parser) throws Exception { Task task = getTestTask(); @@ -1098,8 +1060,6 @@ private ItemPath getConfigurationPropertyPath(QName elementQName) { @Test public void test800GetResourceDummy() throws Exception { - final String TEST_NAME = "test800GetResourceDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1131,27 +1091,14 @@ public void test800GetResourceDummy() throws Exception { @Test public void test820SingleDescriptionModify() throws Exception { - final String TEST_NAME = "test820SingleDescriptionModify"; - Task task = getTestTask(); OperationResult result = task.getResult(); singleModify(descriptionAnt, -1, task, result); } -// @Test -// public void test835ModifySchemaHandling() throws Exception { -// // -// Task task = createTask(TEST_NAME); -// OperationResult result = task.getResult(); -// CarefulAnt ant = ants.get(1); -// singleModify(ant, 0, task, result); -// } - @Test public void test840RandomModifySequence() throws Exception { - final String TEST_NAME = "test840RandomModifySequence"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java index 0a8d0919d3f..c08b4c6591a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java @@ -6,6 +6,29 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.GetOperationOptions.createRaw; +import static com.evolveum.midpoint.schema.GetOperationOptions.createTolerateRawData; + +import java.io.File; +import java.io.FileInputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.BreakMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.prism.*; @@ -30,40 +53,11 @@ import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DisplayableValue; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; -import java.io.FileInputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import static com.evolveum.midpoint.schema.GetOperationOptions.createRaw; -import static com.evolveum.midpoint.schema.GetOperationOptions.createTolerateRawData; -import static org.testng.AssertJUnit.*; - -/** - * @author semancik - * - */ @SuppressWarnings({ "SimplifiedTestNGAssertion", "SameParameterValue" }) -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestStrangeCases extends AbstractInitializedModelIntegrationTest { @@ -122,7 +116,7 @@ public class TestStrangeCases extends AbstractInitializedModelIntegrationTest { private static final File SYSTEM_CONFIGURATION_STRANGE_FILE = new File(TEST_DIR, "system-configuration-strange.xml"); private static final XMLGregorianCalendar USER_DEGHOULASH_FUNERAL_TIMESTAMP = - XmlTypeConverter.createXMLGregorianCalendar(1771, 1, 2, 11, 22, 33); + XmlTypeConverter.createXMLGregorianCalendar(1771, 1, 2, 11, 22, 33); private static final File TREASURE_ISLAND_FILE = new File(TEST_DIR, "treasure-island.txt"); @@ -172,12 +166,12 @@ protected File getSystemConfigurationFile() { * Make sure we can log in as administrator. There are some problems in the * system configuration (e.g. unknown collection). But this should not profibit * login. - * + *

* Note: this will probably die even before it gets to this test. Test class * initialization won't work if administrator cannot log in. But initialization * code may change in the future. Therefore it is better to have also an explicit * test for this. - * + *

* MID-5328 */ @Test @@ -223,9 +217,9 @@ public void test050AddRoleRecursionAssignment() throws Exception { /** * Stupid: see Idiot * Idiot: see Stupid - * + *

* In this case the assignment loop is broken after few attempts. - * + *

* MID-3652 */ @Test @@ -280,10 +274,10 @@ public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() th dummyAuditService.clear(); try { - // WHEN - modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); + // WHEN + modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - AssertJUnit.fail("Unexpected executeChanges success"); + AssertJUnit.fail("Unexpected executeChanges success"); } catch (ObjectAlreadyExistsException e) { // This is expected display("Expected exception", e); @@ -340,7 +334,6 @@ public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() th assertEquals("Wrong number of execution deltas", 0, auditExecution0Deltas.size()); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); - //TODO: enable after fixing the above mentioned problem in ProjectionValueProcessor // // Strictly speaking, there should be just 2 records, not 3. // // But this is a strange case, not a common one. Midpoint does two attempts. @@ -825,7 +818,6 @@ public void test317SearchDeGhoulashByFuneralTimestamp() throws Exception { searchDeGhoulash(PIRACY_FUNERAL_TIMESTAMP, USER_DEGHOULASH_FUNERAL_TIMESTAMP); } - private void searchDeGhoulash(QName propName, T propValue) throws Exception { // GIVEN Task task = getTestTask(); @@ -934,9 +926,9 @@ public void test332AssignDeGhoulashRecursion() throws Exception { /** * Stupid: see Idiot * Idiot: see Stupid - * + *

* In this case the assignment loop is broken after few attempts. - * + *

* MID-3652 */ @Test @@ -963,9 +955,9 @@ public void test334AssignDeGhoulashStupidAssignment() throws Exception { /** * Stupid: see Idiot * Idiot: see Stupid - * + *

* In this case the assignment loop is broken after few attempts. - * + *

* MID-3652 */ @Test @@ -1055,7 +1047,7 @@ public void test350AssignDeGhoulashRoleBadConstructionResourceRef() throws Excep display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); - TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); + TestUtil.assertMessageContains(message, "role:" + ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); @@ -1082,7 +1074,7 @@ public void test351UnAssignDeGhoulashRoleBadConstructionResourceRef() throws Exc display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); - TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); + TestUtil.assertMessageContains(message, "role:" + ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); @@ -1155,7 +1147,7 @@ public void test360AddRoleTargetBadConstructionResourceRef() throws Exception { display("result", result); TestUtil.assertPartialError(result); String message = result.getMessage(); - TestUtil.assertMessageContains(message, "role:"+ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID); + TestUtil.assertMessageContains(message, "role:" + ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction metarole"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); } @@ -1200,7 +1192,7 @@ public void test401ListTasks() throws Exception { display("Tasks", objects); assertEquals("Unexpected number of tasks", 1, objects.size()); boolean found = false; - for (PrismObject object: objects) { + for (PrismObject object : objects) { if (object.getOid().equals(TASK_MOCK_JACK_OID)) { found = true; } @@ -1250,7 +1242,7 @@ public void test410DeleteJack() throws Exception { display("Tasks", objects); assertEquals("Unexpected number of tastsk", 1, objects.size()); PrismObject jackTask = null; - for (PrismObject object: objects) { + for (PrismObject object : objects) { if (object.getOid().equals(TASK_MOCK_JACK_OID)) { jackTask = object; } @@ -1294,7 +1286,7 @@ public void test450AddApprovalCase() throws Exception { assertSuccess(result); assertCaseAfter(CASE_APPROVAL_OID) - .name() + .name() .assertOrig("Assigning role \"Manager\" to user \"vera\""); } @@ -1306,9 +1298,9 @@ public void test500EnumerationExtension() { // WHEN TestUtil.assertSetEquals("Wrong allowedValues in mark", MiscUtil.getValuesFromDisplayableValues(markDef.getAllowedValues()), - "pegLeg","noEye","hook","tatoo","scar","bravery"); + "pegLeg", "noEye", "hook", "tatoo", "scar", "bravery"); - for (DisplayableValue disp: markDef.getAllowedValues()) { + for (DisplayableValue disp : markDef.getAllowedValues()) { if (disp.getValue().equals("pegLeg")) { assertEquals("Wrong pegLeg label", "Peg Leg", disp.getLabel()); } @@ -1418,7 +1410,7 @@ private void changeDefinition(QName piracyShip, ItemName piracyShipBroken) { /** * Read guybrush again. * The operation should fail, because the raw mode itself does not allow raw data (except for some objects). - * + *

* TODO reconsider this eventually, and change the test */ @Test @@ -1441,8 +1433,8 @@ public void test522ShipReadBadRaw() { /** * Read guybrush again. * The operation should fail, because of the plain mode. - * - * TODO reconsider this eventually, and change the test + *

+ * TODO reconsider this eventually, and change the test */ @Test public void test524ShipReadBadPlain() { @@ -1532,7 +1524,7 @@ public void test600AddUserGuybrushAssignAccount() throws Exception { * Set attribute that is not in the schema directly into dummy resource. * Get that account. Make sure that the operations does not die. */ - @Test(enabled=false) // MID-2880 + @Test(enabled = false) // MID-2880 public void test610GetAccountGuybrushRogueAttribute() throws Exception { // GIVEN Task task = getTestTask(); @@ -1557,25 +1549,24 @@ public void test610GetAccountGuybrushRogueAttribute() throws Exception { assertDummyAccountAttribute(null, USER_GUYBRUSH_USERNAME, "rogue", "habakuk"); } - - @SafeVarargs - private final void assertExtension(PrismObject object, QName propName, T... expectedValues) { + private void assertExtension( + PrismObject object, QName propName, T... expectedValues) { PrismContainer extensionContainer = object.findContainer(ObjectType.F_EXTENSION); - assertNotNull("No extension container in "+object, extensionContainer); + assertNotNull("No extension container in " + object, extensionContainer); PrismProperty extensionProperty = extensionContainer.findProperty(ItemName.fromQName(propName)); - assertNotNull("No extension property "+propName+" in "+object, extensionProperty); - PrismAsserts.assertPropertyValues("Values of extension property "+propName, extensionProperty.getValues(), expectedValues); + assertNotNull("No extension property " + propName + " in " + object, extensionProperty); + PrismAsserts.assertPropertyValues("Values of extension property " + propName, extensionProperty.getValues(), expectedValues); } /** * Break the user in the repo by inserting accountRef that points nowhere. */ private void addBrokenAccountRef(String userOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { - OperationResult result = new OperationResult(TestStrangeCases.class.getName() + ".addBrokenAccountRef"); + OperationResult result = createOperationResult("addBrokenAccountRef"); Collection modifications = prismContext.deltaFactory().reference().createModificationAddCollection(UserType.class, UserType.F_LINK_REF, NON_EXISTENT_ACCOUNT_OID); - repositoryService.modifyObject(UserType.class, userOid, modifications , result); + repositoryService.modifyObject(UserType.class, userOid, modifications, result); assertSuccess(result); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/AbstractArchetypesTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/AbstractArchetypesTest.java index bd9ac5ad41f..1eb6c8faf87 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/AbstractArchetypesTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/AbstractArchetypesTest.java @@ -6,8 +6,6 @@ */ package com.evolveum.midpoint.model.intest.archetypes; -import static org.testng.AssertJUnit.assertEquals; - import java.io.File; import org.springframework.test.annotation.DirtiesContext; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestCollections.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestCollections.java index 739febe6312..d75f22cd9b9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestCollections.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestCollections.java @@ -7,9 +7,7 @@ package com.evolveum.midpoint.model.intest.archetypes; import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; import java.util.Collection; import java.util.stream.Collectors; @@ -27,8 +25,6 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectCollectionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyConstraintKindType; @@ -38,14 +34,11 @@ * Test behavior of connectors that have several instances (poolable connectors). * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCollections extends AbstractArchetypesTest { - private static final Trace LOGGER = TraceManager.getTrace(TestCollections.class); - private PrismObject collectionActiveUsers; private CompiledObjectCollectionView collectionViewActiveUsers; private int numberOfDisabledUsers = 0; @@ -63,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -82,8 +73,6 @@ public void test000Sanity() throws Exception { @Test public void test100CompileCollectionView() throws Exception { - final String TEST_NAME = "test100CompileCollectionView"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -99,8 +88,8 @@ public void test100CompileCollectionView() throws Exception { assertNotNull("Null view", collectionActiveUsers); assertObjectCollectionView(collectionViewActiveUsers) - .assertFilter() - .assertDomainFilter(); + .assertFilter() + .assertDomainFilter(); } @@ -109,8 +98,6 @@ public void test100CompileCollectionView() throws Exception { */ @Test public void test102SearchCollectionUsers() throws Exception { - final String TEST_NAME = "test102SearchCollectionUsers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -128,8 +115,6 @@ public void test102SearchCollectionUsers() throws Exception { @Test public void test110CollectionStatsAllEnabled() throws Exception { - final String TEST_NAME = "test110CollectionStatsAllEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -145,14 +130,12 @@ public void test110CollectionStatsAllEnabled() throws Exception { assertNotNull("Null stats", stats); assertEquals("Wrong object count", getNumberOfUsers(), stats.getObjectCount()); - assertEquals("Wrong domain count", (Integer)getNumberOfUsers(), stats.getDomainCount()); + assertEquals("Wrong domain count", (Integer) getNumberOfUsers(), stats.getDomainCount()); assertPercentage(stats, 100); } @Test public void test112EvaluateRulesAllEnabled() throws Exception { - final String TEST_NAME = "test112EvaluateRulesAllEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -166,14 +149,12 @@ public void test112EvaluateRulesAllEnabled() throws Exception { assertSuccess(result); assertEvaluatedPolicyRules(evaluatedRules, collectionActiveUsers) - .single() + .single() .assertNotTriggered(); } @Test public void test120CollectionStatsOneDisabled() throws Exception { - final String TEST_NAME = "test120CollectionStatsOneDisabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -192,14 +173,12 @@ public void test120CollectionStatsOneDisabled() throws Exception { assertNotNull("Null stats", stats); assertEquals("Wrong object count", getNumberOfUsers() - numberOfDisabledUsers, stats.getObjectCount()); - assertEquals("Wrong domain count", (Integer)getNumberOfUsers(), stats.getDomainCount()); - assertPercentage(stats, (Float)((getNumberOfUsers() - numberOfDisabledUsers)*100f)/getNumberOfUsers()); + assertEquals("Wrong domain count", (Integer) getNumberOfUsers(), stats.getDomainCount()); + assertPercentage(stats, (getNumberOfUsers() - numberOfDisabledUsers) * 100f / getNumberOfUsers()); } @Test public void test122EvaluateRulesOneDisabled() throws Exception { - final String TEST_NAME = "test122EvaluateRulesOneDisabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -213,10 +192,10 @@ public void test122EvaluateRulesOneDisabled() throws Exception { assertSuccess(result); assertEvaluatedPolicyRules(evaluatedRules, collectionActiveUsers) - .single() + .single() .assertPolicySituation(POLICY_SITUATION_TOO_MANY_INACTIVE_USERS) .singleTrigger() - .assertConstraintKind(PolicyConstraintKindType.COLLECTION_STATS); + .assertConstraintKind(PolicyConstraintKindType.COLLECTION_STATS); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestAssociationInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestAssociationInbound.java index 1e8f7b62c7a..578cf5700cc 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestAssociationInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestAssociationInbound.java @@ -12,8 +12,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.springframework.test.annotation.DirtiesContext; @@ -29,8 +27,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestAssociationInbound extends AbstractGenericSyncTest { - private static final Trace LOGGER = TraceManager.getTrace(TestAssociationInbound.class); - public static final File RESOURCE_DUMMY_PURPLE_FILE = new File(TEST_DIR, "resource-dummy-purple.xml"); public static final String RESOURCE_DUMMY_PURPLE_OID = "10000000-0000-0000-0000-000000001105"; public static final String RESOURCE_DUMMY_PURPLE_NAME = "purple"; @@ -39,7 +35,6 @@ public class TestAssociationInbound extends AbstractGenericSyncTest { public static final String ACCOUNT_JDOE_OID = "20000000-0000-0000-3333-000000000047"; public static final File ACCOUNT_CREW_FILE = new File(TEST_DIR, "account-crew.xml"); - public static final String ACCOUNT_CREW_OID = "20000000-0000-0000-3333-000000000048"; public static final File USER_JDOE_FILE = new File(TEST_DIR, "user-jdoe.xml"); public static final String USER_JDOE_OID = "fd5039c8-ddc8-11e4-8ec7-001e8c717e5c"; @@ -74,14 +69,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100AssociationInboundMateForOrangeResource() throws Exception { - final String TEST_NAME = "test100AssociationInboundMateForOrangeResource"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject resource = getDummyResourceObject(RESOURCE_DUMMY_PURPLE_NAME); + PrismObject resource = getDummyResourceObject(RESOURCE_DUMMY_PURPLE_NAME); - LOGGER.info("Resource {}", resource); + logger.info("Resource {}", resource); modelService.importFromResource(ACCOUNT_JDOE_OID, task, result); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java index 792da9674d7..4c63e010387 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java @@ -1270,7 +1270,7 @@ public void test261EditShadowSchemaObjectclass() throws Exception { OperationResult result = task.getResult(); ResourceShadowDiscriminator discr = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, dummyResourceCtl.getAccountObjectClassQName()); - IntegrationTestTools.display("Discr", discr); + PrismTestUtil.display("Discr", discr); // WHEN when(); @@ -1302,7 +1302,7 @@ public void test263EditShadowSchemaEmpty() throws Exception { OperationResult result = task.getResult(); ResourceShadowDiscriminator discr = new ResourceShadowDiscriminator(null, null); - IntegrationTestTools.display("Discr", discr); + PrismTestUtil.display("Discr", discr); // WHEN when(); @@ -1548,7 +1548,7 @@ public void test820OtisSearchUsers() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - assertEquals("Unexepected number of users found", 7, users.size()); + assertEquals("Unexpected number of users found", 7, users.size()); for (final PrismObject user: users) { assertProperty(user, UserType.F_NAME, new Validator>() { @@ -1619,7 +1619,7 @@ private void assertPropertyValues(PrismObject objec try { validator.validate(propDef, path.toString()+" (propDef) "); } catch (Exception | Error e) { - IntegrationTestTools.display("Wrong definition", propDef); + PrismTestUtil.display("Wrong definition", propDef); throw e; } } @@ -1633,7 +1633,7 @@ private void assertPropertyValues(PrismObject objec try { validator.validate(propDef, path.toString()+" (propDef) "); } catch (Exception | Error e) { - IntegrationTestTools.display("Wrong definition", propDef); + PrismTestUtil.display("Wrong definition", propDef); throw e; } } @@ -1643,7 +1643,7 @@ private void assertPropertyValues(PrismObject objec try { validator.validate(objPropDef, path.toString()+" (objectDef) "); } catch (Exception | Error e) { - IntegrationTestTools.display("Wrong definition", objPropDef); + PrismTestUtil.display("Wrong definition", objPropDef); throw e; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java index 32e2c4e8228..ea2b2e2a02c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java @@ -6,7 +6,28 @@ */ package com.evolveum.midpoint.model.intest.importer; -import com.evolveum.icf.dummy.resource.DummyResource; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.util.MiscSchemaUtil.getDefaultImportOptions; +import static com.evolveum.midpoint.test.IntegrationTestTools.LOGGER; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.xml.sax.SAXException; + import com.evolveum.midpoint.common.Clock; import com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest; import com.evolveum.midpoint.prism.*; @@ -37,34 +58,11 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.List; - -import static com.evolveum.midpoint.schema.util.MiscSchemaUtil.getDefaultImportOptions; -import static com.evolveum.midpoint.test.IntegrationTestTools.*; -import static org.testng.AssertJUnit.*; - /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) -@DirtiesContext(classMode=ClassMode.AFTER_CLASS) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrationTest { private static final String TEST_FILE_DIRECTORY = "src/test/resources/importer/"; @@ -100,9 +98,6 @@ public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrat private static final String ROLE_ONE_LEGACY_FILE_NAME = "role-one-legacy"; private static final String ROLE_ONE_LEGACY_OID = "0d70504c-d094-11e8-b0cc-675c492577e7"; - private DummyResource dummyResource; - private DummyResourceContoller dummyResourceCtl; - private PrismObject dummyConnector; private PrismObject importedResource; private PrismObject importedRepoResource; @@ -136,9 +131,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(USER_TEMPLATE_SCHEMA_CONSTRAINTS_FILE, initResult); // Just initialize the resource, do NOT import resource definition - dummyResourceCtl = DummyResourceContoller.create(null); + DummyResourceContoller dummyResourceCtl = DummyResourceContoller.create(null); dummyResourceCtl.extendSchemaPirate(); - dummyResource = dummyResourceCtl.getDummyResource(); dummyConnector = findConnectorByTypeAndVersion(CONNECTOR_DUMMY_TYPE, CONNECTOR_DUMMY_VERSION, initResult); @@ -147,7 +141,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti /** * Test integrity of the test setup. - * */ @Test public void test000Integrity() { @@ -158,8 +151,8 @@ public void test000Integrity() { @Test public void test001ImportConnector() throws FileNotFoundException, ObjectNotFoundException, SchemaException { // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test001ImportConnector"); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(CONNECTOR_DBTABLE_FILE_NAME, true)); dummyAuditService.clear(); @@ -178,7 +171,6 @@ public void test001ImportConnector() throws FileNotFoundException, ObjectNotFoun ConnectorType connector = repositoryService.getObject(ConnectorType.class, CONNECOTR_DBTABLE_OID, null, result).asObjectable(); assertNotNull(connector); PrismAsserts.assertEqualsPolyString("Wrong connector name.", "ICF org.identityconnectors.databasetable.DatabaseTableConnector", connector.getName()); -// assertEquals("ICF org.identityconnectors.databasetable.DatabaseTableConnector", connector.getName()); assertEquals(CONNECTOR_NAMESPACE, connector.getNamespace()); assertEquals("org.identityconnectors.databasetable.DatabaseTableConnector", connector.getConnectorType()); @@ -197,8 +189,8 @@ public void test001ImportConnector() throws FileNotFoundException, ObjectNotFoun @Test public void test003ImportUsers() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test003ImportUsers"); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_FILE_NAME, false)); dummyAuditService.clear(); @@ -215,7 +207,7 @@ public void test003ImportUsers() throws Exception { // Check import with fixed OID UserType jack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result).asObjectable(); - display("Jack",jack); + display("Jack", jack); assertNotNull(jack); PrismAsserts.assertEqualsPolyString("wrong givenName", "Jack", jack.getGivenName()); PrismAsserts.assertEqualsPolyString("wrong familyName", "Sparrow", jack.getFamilyName()); @@ -223,8 +215,8 @@ public void test003ImportUsers() throws Exception { PrismAsserts.assertEquals("wrong costCenter", "", jack.getCostCenter()); // Jack has a password. Check if it was encrypted ProtectedStringType protectedString = jack.getCredentials().getPassword().getValue(); - assertNull("Arrgh! Pirate sectrets were revealed!",protectedString.getClearValue()); - assertNotNull("Er? The pirate sectrets were lost!",protectedString.getEncryptedDataType()); + assertNull("Arrgh! Pirate sectrets were revealed!", protectedString.getClearValue()); + assertNotNull("Er? The pirate sectrets were lost!", protectedString.getEncryptedDataType()); assertMetadata(jack, startTime, endTime); @@ -257,8 +249,8 @@ public void test003ImportUsers() throws Exception { @Test public void test004DuplicateImportUsers() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test004DuplicateImportUsers"); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_FILE_NAME, false)); dummyAuditService.clear(); @@ -289,8 +281,8 @@ public void test004DuplicateImportUsers() throws Exception { @Test public void test005ImportUsersWithOverwrite() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test005ImportUsersWithOverwrite"); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_OVERWRITE_FILE_NAME, false)); ImportOptionsType options = getDefaultImportOptions(); options.setOverwrite(true); @@ -308,20 +300,20 @@ public void test005ImportUsersWithOverwrite() throws Exception { // list all users List> users = modelService.searchObjects(UserType.class, prismContext.queryFactory().createQuery(), null, task, result); // Three old users, one new - assertEquals(5,users.size()); + assertEquals(5, users.size()); for (PrismObject user : users) { UserType userType = user.asObjectable(); if (userType.getName().toString().equals("jack")) { // OID and all the attributes should be the same - assertEquals(USER_JACK_OID,userType.getOid()); + assertEquals(USER_JACK_OID, userType.getOid()); PrismAsserts.assertEqualsPolyString("wrong givenName", "Jack", userType.getGivenName()); PrismAsserts.assertEqualsPolyString("wrong familyName", "Sparrow", userType.getFamilyName()); PrismAsserts.assertEqualsPolyString("wrong fullName", "Cpt. Jack Sparrow", userType.getFullName()); } if (userType.getName().toString().equals("will")) { // OID should be the same, and there should be an employee type - assertEquals(USER_WILL_OID,userType.getOid()); + assertEquals(USER_WILL_OID, userType.getOid()); assertTrue("Wrong Will's employee type", userType.getSubtype().contains("legendary")); } if (userType.getName().toString().equals("guybrush")) { @@ -347,13 +339,12 @@ public void test005ImportUsersWithOverwrite() throws Exception { dummyAuditService.assertRecords(8); // 1 failed, 7 succeeded } - // Import the same thing again, with overwrite and also while keeping OIDs @Test public void test006ImportUsersWithOverwriteKeepOid() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test005ImportUsersWithOverwrite"); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_OVERWRITE_FILE_NAME, false)); ImportOptionsType options = getDefaultImportOptions(); options.setOverwrite(true); @@ -367,25 +358,25 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { // THEN result.computeStatus(); display("Result after import with overwrite", result); - TestUtil.assertSuccess("Import failed (result)", result,1); + TestUtil.assertSuccess("Import failed (result)", result, 1); // list all users List> users = modelService.searchObjects(UserType.class, prismContext.queryFactory().createQuery(), null, task, result); // Three old users, one new - assertEquals(5,users.size()); + assertEquals(5, users.size()); for (PrismObject user : users) { UserType userType = user.asObjectable(); if (userType.getName().toString().equals("jack")) { // OID and all the attributes should be the same - assertEquals(USER_JACK_OID,userType.getOid()); + assertEquals(USER_JACK_OID, userType.getOid()); PrismAsserts.assertEqualsPolyString("wrong givenName", "Jack", userType.getGivenName()); PrismAsserts.assertEqualsPolyString("wrong familyName", "Sparrow", userType.getFamilyName()); PrismAsserts.assertEqualsPolyString("wrong fullName", "Cpt. Jack Sparrow", userType.getFullName()); } if (userType.getName().toString().equals("will")) { // OID should be the same, and there should be an employee type - assertEquals(USER_WILL_OID,userType.getOid()); + assertEquals(USER_WILL_OID, userType.getOid()); assertTrue("Wrong Will's employee type", userType.getSubtype().contains("legendary")); } if (userType.getName().toString().equals("guybrush")) { @@ -443,7 +434,7 @@ public void test020ImportTask() throws Exception { assertEquals("xsi:type'd property has incorrect type", Integer.class, delayProp.getValues().get(0).getValue().getClass()); assertEquals("xsi:type'd property not imported correctly", Integer.valueOf(1000), delayProp.getValues().get(0).getValue()); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -470,7 +461,7 @@ public void test030ImportResource() throws Exception { // THEN result.computeStatus(); display("Result after import", result); - TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_FILE_NAME+" has failed (result)", result, 2); + TestUtil.assertSuccess("Import of " + RESOURCE_DUMMY_FILE_NAME + " has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); @@ -523,7 +514,7 @@ public void test031ReimportResource() throws Exception { // THEN result.computeStatus(); display("Result after import", result); - TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_CHANGED_FILE_NAME+" has failed (result)", result, 2); + TestUtil.assertSuccess("Import of " + RESOURCE_DUMMY_CHANGED_FILE_NAME + " has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); @@ -574,7 +565,7 @@ public void test032ImportResourceOidAndFilter() throws Exception { // THEN result.computeStatus(); display("Result after import", result); - TestUtil.assertSuccess("Import of "+RESOURCE_DERBY_FILE_NAME+" has failed (result)", result, 2); + TestUtil.assertSuccess("Import of " + RESOURCE_DERBY_FILE_NAME + " has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); @@ -582,20 +573,20 @@ public void test032ImportResourceOidAndFilter() throws Exception { display("Imported resource (repo)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, - CONNECOTR_DBTABLE_OID, true); + CONNECOTR_DBTABLE_OID); importedResource = modelService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, task, result); display("Imported resource (model)", importedResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, - CONNECOTR_DBTABLE_OID, false); + CONNECOTR_DBTABLE_OID); // Read it from repo again. The read from model triggers schema fetch which increases version importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); display("Imported resource (repo2)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, - CONNECOTR_DBTABLE_OID, true); + CONNECOTR_DBTABLE_OID); // Check audit display("Audit", dummyAuditService); @@ -627,36 +618,34 @@ public void test033ImportResourceDummyRuntime() throws Exception { // THEN result.computeStatus(); display("Result after import", result); - TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_RUNTIME_FILE_NAME+" has failed (result)", result, 2); + TestUtil.assertSuccess("Import of " + RESOURCE_DUMMY_RUNTIME_FILE_NAME + " has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, result); display("Imported resource (repo)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); - assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null, true); + assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null); importedResource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, task, result); display("Imported resource (model)", importedResource); IntegrationTestTools.assertNoRepoCache(); - assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null,false); + assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null); // Read it from repo again. The read from model triggers schema fetch which increases version importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, result); display("Imported resource (repo2)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); - assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null, true); + assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null); } @Test public void test040ImportUserHermanNoEncryption() throws Exception { - final String TEST_NAME = "test040ImportUserHermanNoEncryption"; // GIVEN - InternalsConfig.readEncryptionChecks = false; - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(USER_HERMAN_FILE_NAME, true)); ImportOptionsType importOptions = getDefaultImportOptions(); @@ -696,11 +685,9 @@ public void test040ImportUserHermanNoEncryption() throws Exception { @Test public void test050ImportUserHermanOverwriteFullProcessing() throws Exception { - final String TEST_NAME = "test050ImportUserHermanOverwriteFullProcessing"; // GIVEN - - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(USER_HERMAN_FILE_NAME, true)); ImportOptionsType importOptions = getDefaultImportOptions(); @@ -740,11 +727,9 @@ public void test050ImportUserHermanOverwriteFullProcessing() throws Exception { @Test public void test060ImportConstrainedWrongFullProcessing() throws Exception { - final String TEST_NAME = "test060ImportConstrainedWrongFullProcessing"; // GIVEN - - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(USER_CONSTRAINED_WRONG_FILE_NAME, false)); ImportOptionsType importOptions = getDefaultImportOptions(); @@ -777,11 +762,10 @@ public void test060ImportConstrainedWrongFullProcessing() throws Exception { @Test public void test070ImportConstrainedWrong() throws Exception { - final String TEST_NAME = "test070ImportConstrainedWrong"; // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(USER_CONSTRAINED_WRONG_FILE_NAME, false)); ImportOptionsType importOptions = getDefaultImportOptions(); @@ -802,20 +786,13 @@ public void test070ImportConstrainedWrong() throws Exception { // Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(2); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(1); -// dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class); -// dummyAuditService.assertExecutionSuccess(); } @Test public void test100GoodRefImport() throws Exception { - final String TEST_NAME = "test100GoodRefImport"; // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." +TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_REF_FILE_NAME, false)); // WHEN @@ -826,8 +803,6 @@ public void test100GoodRefImport() throws Exception { display("Result after good import", result); TestUtil.assertSuccessOrWarning("Import has failed (result)", result, 2); - // EqualsFilter equal = EqualsFilter.createEqual(UserType.F_NAME, UserType.class, PrismTestUtil.getPrismContext(), null, "jack"); - // ObjectQuery query = ObjectQuery.createObjectQuery(equal); ObjectQuery query = ObjectQueryUtil.createNameQuery("jack", PrismTestUtil.getPrismContext()); List> users = repositoryService.searchObjects(UserType.class, query, null, result); @@ -844,10 +819,9 @@ public void test100GoodRefImport() throws Exception { @Test public void test200BadImport() throws Exception { - final String TEST_NAME = "test200BadImport"; // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(BAD_IMPORT_FILE_NAME, false)); repositoryService.deleteObject(UserType.class, USER_JACK_OID, result); @@ -875,10 +849,9 @@ public void test200BadImport() throws Exception { */ @Test public void test210ImportRoleOneLegacyDefault() throws Exception { - final String TEST_NAME = "test210ImportRoleOneLegacyDefault"; // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(ROLE_ONE_LEGACY_FILE_NAME, false)); // WHEN @@ -899,10 +872,9 @@ public void test210ImportRoleOneLegacyDefault() throws Exception { */ @Test public void test212ImportRoleOneLegacyCompat() throws Exception { - final String TEST_NAME = "test212ImportRoleOneLegacyCompat"; // GIVEN - Task task = taskManager.createTaskInstance(); - OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(ROLE_ONE_LEGACY_FILE_NAME, false)); ImportOptionsType options = getDefaultImportOptions(); options.setCompatMode(true); @@ -922,7 +894,7 @@ public void test212ImportRoleOneLegacyCompat() throws Exception { private void assertDummyResource(PrismObject resource, boolean fromRepo) { PrismContainer configurationPropertiesContainer = assertResource(resource, "Dummy Resource", RESOURCE_DUMMY_NAMESPACE, - dummyConnector.getOid(), fromRepo); + dummyConnector.getOid()); PrismProperty guardedProperty = configurationPropertiesContainer.findProperty( new ItemName(CONNECTOR_DUMMY_NAMESPACE, "uselessGuardedString")); // The resource was pulled from the repository. Therefore it does not have the right schema here. We should proceed with caution @@ -933,7 +905,7 @@ private void assertDummyResource(PrismObject resource, boolean fro if (fromRepo) { Object passwordRawElement = guardedPVal.getRawElement(); if (!(passwordRawElement instanceof MapXNode)) { - AssertJUnit.fail("Expected password value of type "+ MapXNode.class+" but got "+passwordRawElement.getClass()); + AssertJUnit.fail("Expected password value of type " + MapXNode.class + " but got " + passwordRawElement.getClass()); } MapXNode passwordXNode = (MapXNode) passwordRawElement; assertTrue("uselessGuardedString was not encrypted (clearValue)", passwordXNode.get(new QName("clearValue")) == null); @@ -945,18 +917,18 @@ private void assertDummyResource(PrismObject resource, boolean fro } } - private PrismContainer assertResource(PrismObject resource, String resourceName, String namespace, - String connectorOid, boolean fromRepo) { + private PrismContainer assertResource(PrismObject resource, + String resourceName, String namespace, String connectorOid) { ResourceType resourceType = resource.asObjectable(); assertNotNull(resourceType); PrismAsserts.assertEqualsPolyString("Wrong resource name", resourceName, resourceType.getName()); - assertEquals("Wrong namespace of "+resource, namespace, ResourceTypeUtil.getResourceNamespace(resourceType)); - assertEquals("Wrong connector OID in "+resource, connectorOid, resourceType.getConnectorRef().getOid()); + assertEquals("Wrong namespace of " + resource, namespace, ResourceTypeUtil.getResourceNamespace(resourceType)); + assertEquals("Wrong connector OID in " + resource, connectorOid, resourceType.getConnectorRef().getOid()); // The password in the resource configuration should be encrypted after import PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); PrismContainer configurationPropertiesContainer = - configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); + configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); assertNotNull("No configurationProperties in resource", configurationPropertiesContainer); return configurationPropertiesContainer; @@ -964,11 +936,10 @@ private PrismContainer assertResource(PrismObject r private void assertMetadata(O objectType, XMLGregorianCalendar startTime, XMLGregorianCalendar endTime) { MetadataType metadata = objectType.getMetadata(); - assertNotNull("No metadata in "+objectType, metadata); + assertNotNull("No metadata in " + objectType, metadata); XMLGregorianCalendar createTimestamp = metadata.getCreateTimestamp(); - assertNotNull("No createTimestamp in metadata of "+objectType, createTimestamp); - TestUtil.assertBetween("Wrong createTimestamp in metadata of "+objectType, startTime, endTime, createTimestamp); - assertEquals("Wrong channel in metadata of "+objectType, SchemaConstants.CHANNEL_OBJECT_IMPORT_URI, metadata.getCreateChannel()); + assertNotNull("No createTimestamp in metadata of " + objectType, createTimestamp); + TestUtil.assertBetween("Wrong createTimestamp in metadata of " + objectType, startTime, endTime, createTimestamp); + assertEquals("Wrong channel in metadata of " + objectType, SchemaConstants.CHANNEL_OBJECT_IMPORT_URI, metadata.getCreateChannel()); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java index 687ebaf670e..ceceffed8b4 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java @@ -1454,7 +1454,7 @@ protected void cleanupUser(String userOid, String username, String accountOid) t */ @Test public void test500AssignWillRoleOne() throws Exception { - assignWillRoleOne("test500AssignWillRoleOne", USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assignWillRoleOne(USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); } /** @@ -1826,7 +1826,7 @@ public void test519CleanUp() throws Exception { */ @Test public void test520AssignWillRoleOne() throws Exception { - assignWillRoleOne("test520AssignWillRoleOne", USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assignWillRoleOne(USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); } @@ -1860,7 +1860,7 @@ public void test522AssignWillRoleTwoValidFrom() throws Exception { accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME_PIRATE, PendingOperationExecutionStatusType.EXECUTION_PENDING); } @@ -2141,13 +2141,13 @@ public void test810AssignAccountWill() throws Exception { modifyUserReplace(userWillOid, UserType.F_FULL_NAME, task, result, createPolyString(USER_WILL_FULL_NAME)); // WHEN - assignWillRoleOne(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assignWillRoleOne(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); // THEN restartTask(TASK_SHADOW_REFRESH_OID); waitForTaskFinish(TASK_SHADOW_REFRESH_OID, false); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); } @Test @@ -2176,15 +2176,15 @@ public void test820AssignAccountJack() throws Exception { accountJackReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountJackAfterAssign(TEST_NAME); + assertAccountJackAfterAssign(); // THEN restartTask(TASK_SHADOW_REFRESH_OID); waitForTaskFinish(TASK_SHADOW_REFRESH_OID, false); - assertAccountJackAfterAssign(TEST_NAME); + assertAccountJackAfterAssign(); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); } @Test @@ -2209,9 +2209,9 @@ public void test830CloseCaseWillAndWaitForRefresh() throws Exception { accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertWillAfterCreateCaseClosed(TEST_NAME, false); + assertWillAfterCreateCaseClosed(false); - assertAccountJackAfterAssign(TEST_NAME); + assertAccountJackAfterAssign(); } @Test diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractGroupingManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractGroupingManualResourceTest.java index 5d527898428..3d4d8bdb0d8 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractGroupingManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractGroupingManualResourceTest.java @@ -6,15 +6,11 @@ */ package com.evolveum.midpoint.model.intest.manual; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.io.File; - import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.prism.xml.ns._public.types_3.RawType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -31,21 +27,14 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.asserter.ShadowAsserter; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; +import com.evolveum.prism.xml.ns._public.types_3.RawType; /** * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public abstract class AbstractGroupingManualResourceTest extends AbstractManualResourceTest { @@ -78,8 +67,6 @@ public abstract class AbstractGroupingManualResourceTest extends AbstractManualR protected static final File TASK_PROPAGATION_MULTI_FILE = new File(TEST_DIR, "task-propagation-multi.xml"); protected static final String TASK_PROPAGATION_MULTI_OID = "01db4542-f224-11e7-8833-bbe6634814e7"; - private static final Trace LOGGER = TraceManager.getTrace(AbstractGroupingManualResourceTest.class); - protected String propagationTaskOid = null; protected XMLGregorianCalendar accountWillExecutionTimestampStart; protected XMLGregorianCalendar accountWillExecutionTimestampEnd; @@ -116,7 +103,7 @@ protected void assertFinishedPropagationTask(Task finishedTask, OperationResultS display("Finished propagation task", finishedTask); OperationResultStatusType resultStatus = finishedTask.getResultStatus(); if (expectedStatus == null) { - if ( resultStatus != OperationResultStatusType.SUCCESS && resultStatus != OperationResultStatusType.IN_PROGRESS ) { + if (resultStatus != OperationResultStatusType.SUCCESS && resultStatus != OperationResultStatusType.IN_PROGRESS) { fail("Unexpected propagation task result " + resultStatus); } } else { @@ -138,7 +125,8 @@ protected PendingOperationExecutionStatusType getExpectedExecutionStatus(Pending protected OperationResultStatusType getExpectedResultStatus(PendingOperationExecutionStatusType executionStage) { if (executionStage == PendingOperationExecutionStatusType.EXECUTION_PENDING) { return null; - } if (executionStage == PendingOperationExecutionStatusType.EXECUTING) { + } + if (executionStage == PendingOperationExecutionStatusType.EXECUTING) { return OperationResultStatusType.IN_PROGRESS; } return null; @@ -150,7 +138,7 @@ public void test100AssignWillRoleOne() throws Exception { // The count will be checked only after propagation was run, so we can address both direct and grouping cases rememberCounter(InternalCounters.CONNECTOR_MODIFICATION_COUNT); - assignWillRoleOne("test100AssignWillRoleOne", USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assignWillRoleOne(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); // No counter increment asserted here. Connector instance is initialized in propagation. Not yet. assertSteadyResources(); @@ -162,7 +150,6 @@ public void test100AssignWillRoleOne() throws Exception { */ @Test public void test220ModifyUserWillDisable() throws Exception { - final String TEST_NAME = "test220ModifyUserWillDisable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -242,7 +229,6 @@ public void test220ModifyUserWillDisable() throws Exception { */ @Test public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { - final String TEST_NAME = "test230ModifyAccountWillChangePasswordAndEnable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -268,10 +254,10 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountWillAfterChangePasswordAndEnable(TEST_NAME); + assertAccountWillAfterChangePasswordAndEnable(); } - protected void assertAccountWillAfterChangePasswordAndEnable(final String TEST_NAME) throws Exception { + protected void assertAccountWillAfterChangePasswordAndEnable() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -335,19 +321,11 @@ protected void assertAccountWillAfterChangePasswordAndEnable(final String TEST_N */ @Test public void test232RunPropagationBeforeInterval() throws Exception { - final String TEST_NAME = "test235RunPropagationAfterInterval"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN when(); runPropagation(); - // THEN then(); - - assertAccountWillAfterChangePasswordAndEnable(TEST_NAME); + assertAccountWillAfterChangePasswordAndEnable(); } /** @@ -356,8 +334,7 @@ public void test232RunPropagationBeforeInterval() throws Exception { */ @Test public void test235RunPropagationAfterInterval() throws Exception { - final String TEST_NAME = "test235RunPropagationAfterInterval"; - // GIVEN + given(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -365,13 +342,10 @@ public void test235RunPropagationAfterInterval() throws Exception { accountWillExecutionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); runPropagation(); - // THEN then(); - accountWillExecutionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); @@ -463,7 +437,6 @@ public void test235RunPropagationAfterInterval() throws Exception { */ @Test public void test240CloseCaseAndReadAccountWill() throws Exception { - final String TEST_NAME = "test240CloseCaseAndReadAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -483,7 +456,7 @@ public void test240CloseCaseAndReadAccountWill() throws Exception { accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountWillAfterChangePasswordAndEnableCaseClosed(TEST_NAME, shadowModel); + assertAccountWillAfterChangePasswordAndEnableCaseClosed(shadowModel); } @@ -492,7 +465,6 @@ public void test240CloseCaseAndReadAccountWill() throws Exception { */ @Test public void test250RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test250RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -510,7 +482,7 @@ public void test250RecomputeWillAfter5min() throws Exception { then(); assertSuccess(result); - assertAccountWillAfterChangePasswordAndEnableCaseClosed(TEST_NAME, null); + assertAccountWillAfterChangePasswordAndEnableCaseClosed(null); } /** @@ -519,7 +491,6 @@ public void test250RecomputeWillAfter5min() throws Exception { */ @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -539,28 +510,28 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { assertSuccess(result); ShadowAsserter shadowModelAsserter = ShadowAsserter.forShadow(shadowModel, "model") - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE) .end() - .pendingOperations() + .pendingOperations() .assertOperations(3) .end(); assertAttributeFromBackingStore(shadowModelAsserter, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelAsserter); assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .assertOperations(3); ShadowAsserter shadowModelFutureAsserter = assertModelShadowFuture(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE) .end(); @@ -576,7 +547,6 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test273GetAccountWill() throws Exception { - final String TEST_NAME = "test273GetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -594,28 +564,28 @@ public void test273GetAccountWill() throws Exception { assertSuccess(result); ShadowAsserter shadowModelAsserter = ShadowAsserter.forShadow(shadowModel, "model") - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE) .end() - .pendingOperations() + .pendingOperations() .assertOperations(2) .end(); assertAttributeFromBackingStore(shadowModelAsserter, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelAsserter); assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .assertOperations(2); ShadowAsserter shadowModelFutureAsserter = assertModelShadowFuture(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE) .end(); @@ -631,7 +601,6 @@ public void test273GetAccountWill() throws Exception { */ @Test public void test290RecomputeWillAfter15min() throws Exception { - final String TEST_NAME = "test290RecomputeWillAfter15min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -690,7 +659,6 @@ public void test290RecomputeWillAfter15min() throws Exception { @Test public void test300UnassignAccountWill() throws Exception { - final String TEST_NAME = "test300UnassignAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -765,7 +733,6 @@ public void test300UnassignAccountWill() throws Exception { */ @Test public void test302RunPropagationAfterInterval() throws Exception { - final String TEST_NAME = "test302RunPropagationAfterInterval"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -840,7 +807,6 @@ public void test302RunPropagationAfterInterval() throws Exception { */ @Test public void test310CloseCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test310CloseCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -867,7 +833,7 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - assertUnassignedShadow(shadowRepo, null); + assertUnassignedShadow(shadowRepo); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); @@ -876,11 +842,11 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); - assertUnassignedShadow(shadowModel, ActivationStatusType.ENABLED); // backing store not yet updated + assertUnassignedShadow(shadowModel); // backing store not yet updated assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, - accountWillReqestTimestampStart, accountWillReqestTimestampEnd, + assertSinglePendingOperation( + shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -891,7 +857,6 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { @Test public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { - final String TEST_NAME = "test330UpdateBackingStoreAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -913,7 +878,7 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - assertUnassignedShadow(shadowRepo, null); + assertUnassignedShadow(shadowRepo); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); @@ -922,9 +887,9 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); - assertUnassignedShadow(shadowModel, ActivationStatusType.DISABLED); + assertUnassignedShadow(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -939,18 +904,17 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { */ @Test public void test349CleanUp() throws Exception { - final String TEST_NAME = "test349CleanUp"; - cleanupUser(userWillOid, USER_WILL_NAME, accountWillOid); } // TODO: test400: create -> modify -> propagation - protected void assertUnassignedShadow(PrismObject shadow, ActivationStatusType expectAlternativeActivationStatus) { + protected void assertUnassignedShadow(PrismObject shadow) { assertShadowDead(shadow); } - protected void assertAccountWillAfterChangePasswordAndEnableCaseClosed(final String TEST_NAME, PrismObject shadowModel) throws Exception { + protected void assertAccountWillAfterChangePasswordAndEnableCaseClosed( + PrismObject shadowModel) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1016,7 +980,6 @@ protected void assertAccountWillAfterChangePasswordAndEnableCaseClosed(final Str accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertEquals("Case ID mismatch", willLastCaseOid, pendingOperation2.getAsynchronousOperationReference()); - PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), @@ -1034,5 +997,4 @@ protected void assertAccountWillAfterChangePasswordAndEnableCaseClosed(final Str assertCaseState(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java index 271fe7c6c52..e84c5cf1ecd 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java @@ -6,32 +6,16 @@ */ package com.evolveum.midpoint.model.intest.manual; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; - import javax.xml.bind.JAXBElement; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.test.util.ParallelTestThread; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import com.evolveum.prism.xml.ns._public.types_3.ObjectType; -import com.evolveum.prism.xml.ns._public.types_3.RawType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -42,14 +26,13 @@ import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest; +import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemName; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.CapabilityUtil; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.PointInTimeType; -import com.evolveum.midpoint.schema.SearchResultList; -import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.*; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.internals.InternalCounters; @@ -66,37 +49,25 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.ShadowAsserter; +import com.evolveum.midpoint.test.util.ParallelTestThread; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ImportOptionsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CachingMetadataType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilitiesType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionActionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.AbstractWriteCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CreateCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ReadCapabilityType; -import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; -import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; -import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; +import com.evolveum.prism.xml.ns._public.types_3.ObjectType; +import com.evolveum.prism.xml.ns._public.types_3.*; /** * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public abstract class AbstractManualResourceTest extends AbstractConfiguredModelIntegrationTest { @@ -231,12 +202,12 @@ protected BackingStore createBackingStore() { private PrismObject createUserWill() throws SchemaException { PrismObject user = prismContext.createObject(UserType.class); user.asObjectable() - .name(USER_WILL_NAME) - .givenName(USER_WILL_GIVEN_NAME) - .familyName(USER_WILL_FAMILY_NAME) - .fullName(USER_WILL_FULL_NAME) - .beginActivation().administrativeStatus(ActivationStatusType.ENABLED).end() - .beginCredentials().beginPassword().beginValue().setClearValue(USER_WILL_PASSWORD_OLD); + .name(USER_WILL_NAME) + .givenName(USER_WILL_GIVEN_NAME) + .familyName(USER_WILL_FAMILY_NAME) + .fullName(USER_WILL_FULL_NAME) + .beginActivation().administrativeStatus(ActivationStatusType.ENABLED).end() + .beginCredentials().beginPassword().beginValue().setClearValue(USER_WILL_PASSWORD_OLD); return user; } @@ -262,13 +233,10 @@ protected boolean hasMultivalueInterests() { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; + OperationResult result = getTestOperationResult(); - OperationResult result = new OperationResult(AbstractManualResourceTest.class.getName() - + "." + TEST_NAME); - - ResourceType repoResource = repositoryService.getObject(ResourceType.class, getResourceOid(), - null, result).asObjectable(); + ResourceType repoResource = repositoryService.getObject( + ResourceType.class, getResourceOid(), null, result).asObjectable(); assertNotNull("No connector ref", repoResource.getConnectorRef()); String connectorOid = repoResource.getConnectorRef().getOid(); @@ -289,11 +257,10 @@ public void test000Sanity() throws Exception { @Test public void test012TestConnection() throws Exception { - final String TEST_NAME = "test012TestConnection"; - testConnection(TEST_NAME, false); + testConnection(false); } - public void testConnection(final String TEST_NAME, boolean initialized) throws Exception { + public void testConnection(boolean initialized) throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -370,10 +337,8 @@ protected boolean nativeCapabilitiesEntered() { @Test public void test014Configuration() throws Exception { - final String TEST_NAME = "test014Configuration"; // GIVEN - OperationResult result = new OperationResult(AbstractManualResourceTest.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); // WHEN resource = modelService.getObject(ResourceType.class, getResourceOid(), null, null, result); @@ -436,14 +401,12 @@ public void test016ParsedSchema() throws Exception { @Test public void test017Capabilities() throws Exception { - final String TEST_NAME = "test017Capabilities"; - testCapabilities(TEST_NAME); + testCapabilities(); } - public void testCapabilities(final String TEST_NAME) throws Exception { - + public void testCapabilities() throws Exception { // GIVEN - OperationResult result = new OperationResult(AbstractManualResourceTest.class.getName()+"."+TEST_NAME); + OperationResult result = getTestOperationResult(); // WHEN ResourceType resource = modelService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); @@ -459,7 +422,7 @@ public void testCapabilities(final String TEST_NAME) throws Exception { CapabilityCollectionType nativeCapabilities = capabilities.getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); - assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); + assertFalse("Empty capabilities returned", nativeCapabilitiesList.isEmpty()); CreateCapabilityType capCreate = CapabilityUtil.getCapability(nativeCapabilitiesList, CreateCapabilityType.class); assertNotNull("Missing create capability", capCreate); @@ -469,12 +432,12 @@ public void testCapabilities(final String TEST_NAME) throws Exception { assertNotNull("Missing activation capability", capAct); ReadCapabilityType capRead = CapabilityUtil.getCapability(nativeCapabilitiesList, ReadCapabilityType.class); - assertNotNull("Missing read capability" ,capRead); + assertNotNull("Missing read capability", capRead); assertEquals("Wrong caching-only setting in read capability", Boolean.TRUE, capRead.isCachingOnly()); List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { - System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); + System.out.println("Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } assertSteadyResources(); @@ -485,44 +448,39 @@ public void testCapabilities(final String TEST_NAME) throws Exception { */ @Test public void test018ResourceCaching() throws Exception { - final String TEST_NAME = "test018ResourceCaching"; - testResourceCaching(TEST_NAME); + testResourceCaching(); } - public void testResourceCaching(final String TEST_NAME) throws Exception { + public void testResourceCaching() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject resourceReadonlyBefore = modelService.getObject( - ResourceType.class, getResourceOid(), GetOperationOptions.createReadOnlyCollection(), task, result); + modelService.getObject(ResourceType.class, getResourceOid(), + GetOperationOptions.createReadOnlyCollection(), task, result); assertSteadyResources(); // WHEN when(); - PrismObject resourceReadOnlyAgain = modelService.getObject( - ResourceType.class, getResourceOid(), GetOperationOptions.createReadOnlyCollection(), task, result); + modelService.getObject(ResourceType.class, getResourceOid(), + GetOperationOptions.createReadOnlyCollection(), task, result); assertSteadyResources(); // WHEN when(); - PrismObject resourceAgain = modelService.getObject( - ResourceType.class, getResourceOid(), null, task, result); + modelService.getObject(ResourceType.class, getResourceOid(), null, task, result); // THEN then(); assertSuccess(result); -// assertTrue("Resource instance changed", resourceBefore == resourceReadOnlyAgain); - assertSteadyResources(); } @Test public void test020ReimportResource() throws Exception { - final String TEST_NAME = "test020ReimportResource"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -541,14 +499,12 @@ public void test020ReimportResource() throws Exception { @Test public void test022TestConnection() throws Exception { - final String TEST_NAME = "test022TestConnection"; - testConnection(TEST_NAME, false); + testConnection(false); } @Test public void test027Capabilities() throws Exception { - final String TEST_NAME = "test027Capabilities"; - testCapabilities(TEST_NAME); + testCapabilities(); } /** @@ -556,13 +512,11 @@ public void test027Capabilities() throws Exception { */ @Test public void test028ResourceCaching() throws Exception { - final String TEST_NAME = "test028ResourceCaching"; - testResourceCaching(TEST_NAME); + testResourceCaching(); } @Test public void test030ReimportResourceAgain() throws Exception { - final String TEST_NAME = "test030ReimportResourceAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -582,7 +536,6 @@ public void test030ReimportResourceAgain() throws Exception { // This time simply try to use the resource without any attempt to test connection @Test public void test032UseResource() throws Exception { - final String TEST_NAME = "test032UseResource"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -598,7 +551,7 @@ public void test032UseResource() throws Exception { assertSuccess(result); display("Found accounts", accounts); - assertEquals("unexpected accounts: "+accounts, 0, accounts.size()); + assertEquals("unexpected accounts: " + accounts, 0, accounts.size()); rememberSteadyResources(); @@ -637,8 +590,7 @@ public void test032UseResource() throws Exception { @Test public void test037Capabilities() throws Exception { - final String TEST_NAME = "test037Capabilities"; - testCapabilities(TEST_NAME); + testCapabilities(); } /** @@ -646,8 +598,7 @@ public void test037Capabilities() throws Exception { */ @Test public void test038ResourceCaching() throws Exception { - final String TEST_NAME = "test038ResourceCaching"; - testResourceCaching(TEST_NAME); + testResourceCaching(); } /** @@ -656,8 +607,7 @@ public void test038ResourceCaching() throws Exception { */ @Test public void test099TestConnection() throws Exception { - final String TEST_NAME = "test099TestConnection"; - testConnection(TEST_NAME, true); + testConnection(true); } @Test @@ -665,7 +615,7 @@ public void test100AssignWillRoleOne() throws Exception { // The count will be checked only after propagation was run, so we can address both direct and grouping cases rememberCounter(InternalCounters.CONNECTOR_MODIFICATION_COUNT); - assignWillRoleOne("test100AssignWillRoleOne", USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assignWillRoleOne(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0, 1); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_CONFIGURATION_COUNT, 0, 1); @@ -674,12 +624,11 @@ public void test100AssignWillRoleOne() throws Exception { @Test public void test101GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test101GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); // WHEN when(); @@ -707,7 +656,6 @@ public void test101GetAccountWillFuture() throws Exception { @Test public void test102RecomputeWill() throws Exception { - final String TEST_NAME = "test102RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -720,7 +668,7 @@ public void test102RecomputeWill() throws Exception { then(); assertSuccess(result); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); assertSteadyResources(); } @@ -730,7 +678,6 @@ public void test102RecomputeWill() throws Exception { */ @Test public void test103RunPropagation() throws Exception { - final String TEST_NAME = "test103RunPropagation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -749,7 +696,7 @@ public void test103RunPropagation() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0, 1); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_CONFIGURATION_COUNT, 0, 1); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); assertSteadyResources(); } @@ -771,7 +718,7 @@ public void test104RecomputeWill() throws Exception { assertSuccess(result); assertCounterIncrement(InternalCounters.CONNECTOR_MODIFICATION_COUNT, 0); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); assertSteadyResources(); } @@ -782,8 +729,6 @@ public void test104RecomputeWill() throws Exception { */ @Test public void test105RunPropagationAgain() throws Exception { - final String TEST_NAME = "test105RunPropagationAgain"; - // GIVEN rememberCounter(InternalCounters.CONNECTOR_MODIFICATION_COUNT); @@ -795,7 +740,7 @@ public void test105RunPropagationAgain() throws Exception { then(); assertCounterIncrement(InternalCounters.CONNECTOR_MODIFICATION_COUNT, 0); - assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); + assertAccountWillAfterAssign(USER_WILL_FULL_NAME, PendingOperationExecutionStatusType.EXECUTING); assertSteadyResources(); } @@ -806,7 +751,6 @@ public void test105RunPropagationAgain() throws Exception { */ @Test public void test106AddToBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test106AddToBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -850,12 +794,11 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { @Test public void test108GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test108GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); // WHEN when(); @@ -897,7 +840,6 @@ public void test108GetAccountWillFuture() throws Exception { */ @Test public void test110CloseCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test110CloseCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -917,7 +859,7 @@ public void test110CloseCaseAndRecomputeWill() throws Exception { accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertWillAfterCreateCaseClosed(TEST_NAME, true); + assertWillAfterCreateCaseClosed(true); assertSteadyResources(); } @@ -928,8 +870,6 @@ public void test110CloseCaseAndRecomputeWill() throws Exception { */ @Test public void test114RunPropagation() throws Exception { - final String TEST_NAME = "test114RunPropagation"; - // GIVEN rememberCounter(InternalCounters.CONNECTOR_MODIFICATION_COUNT); @@ -941,7 +881,7 @@ public void test114RunPropagation() throws Exception { then(); assertCounterIncrement(InternalCounters.CONNECTOR_MODIFICATION_COUNT, 0); - assertWillAfterCreateCaseClosed(TEST_NAME, true); + assertWillAfterCreateCaseClosed(true); assertSteadyResources(); } @@ -951,7 +891,6 @@ public void test114RunPropagation() throws Exception { */ @Test public void test120RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test120RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -967,20 +906,20 @@ public void test120RecomputeWillAfter5min() throws Exception { assertSuccess(result); assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertModelShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertCaseState(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); @@ -993,7 +932,6 @@ public void test120RecomputeWillAfter5min() throws Exception { */ @Test public void test130RecomputeWillAfter25min() throws Exception { - final String TEST_NAME = "test130RecomputeWillAfter25min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1009,20 +947,20 @@ public void test130RecomputeWillAfter25min() throws Exception { assertSuccess(result); assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertModelShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertCaseState(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); @@ -1035,7 +973,6 @@ public void test130RecomputeWillAfter25min() throws Exception { */ @Test public void test132RecomputeWillAfter32min() throws Exception { - final String TEST_NAME = "test132RecomputeWillAfter32min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1051,11 +988,11 @@ public void test132RecomputeWillAfter32min() throws Exception { assertSuccess(result); assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .assertNone(); assertModelShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .assertNone(); assertCaseState(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); @@ -1065,7 +1002,6 @@ public void test132RecomputeWillAfter32min() throws Exception { @Test public void test200ModifyUserWillFullname() throws Exception { - final String TEST_NAME = "test200ModifyUserWillFullname"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1088,14 +1024,13 @@ public void test200ModifyUserWillFullname() throws Exception { accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountWillAfterFullNameModification(TEST_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterFullNameModification(PendingOperationExecutionStatusType.EXECUTION_PENDING); assertSteadyResources(); } @Test public void test202RecomputeWill() throws Exception { - final String TEST_NAME = "test202RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1108,14 +1043,13 @@ public void test202RecomputeWill() throws Exception { then(); assertSuccess(result); - assertAccountWillAfterFullNameModification(TEST_NAME, PendingOperationExecutionStatusType.EXECUTION_PENDING); + assertAccountWillAfterFullNameModification(PendingOperationExecutionStatusType.EXECUTION_PENDING); assertSteadyResources(); } @Test public void test203RunPropagation() throws Exception { - final String TEST_NAME = "test203RunPropagation"; // GIVEN clockForward("PT2M"); @@ -1127,14 +1061,13 @@ public void test203RunPropagation() throws Exception { // THEN then(); - assertAccountWillAfterFullNameModification(TEST_NAME, PendingOperationExecutionStatusType.EXECUTING); + assertAccountWillAfterFullNameModification(PendingOperationExecutionStatusType.EXECUTING); assertSteadyResources(); } @Test public void test204RecomputeWill() throws Exception { - final String TEST_NAME = "test204RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1147,7 +1080,7 @@ public void test204RecomputeWill() throws Exception { then(); assertSuccess(result); - assertAccountWillAfterFullNameModification(TEST_NAME, PendingOperationExecutionStatusType.EXECUTING); + assertAccountWillAfterFullNameModification(PendingOperationExecutionStatusType.EXECUTING); assertSteadyResources(); } @@ -1157,7 +1090,6 @@ public void test204RecomputeWill() throws Exception { */ @Test public void test206CloseCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test206CloseCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1205,7 +1137,7 @@ public void test206CloseCaseAndRecomputeWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -1228,13 +1160,11 @@ public void test206CloseCaseAndRecomputeWill() throws Exception { assertSteadyResources(); } - /** * ff 5min, everything should be the same (grace not expired yet) */ @Test public void test210RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test210RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1268,7 +1198,7 @@ public void test210RecomputeWillAfter5min() throws Exception { assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -1293,7 +1223,6 @@ public void test210RecomputeWillAfter5min() throws Exception { @Test public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test212UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1315,7 +1244,7 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -1354,7 +1283,6 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test400PhantomAccount() throws Exception { - final String TEST_NAME = "test400PhantomAccount"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1374,7 +1302,7 @@ public void test400PhantomAccount() throws Exception { // sometimes it is just success. OperationResultStatus status = result.getStatus(); if (status != OperationResultStatus.IN_PROGRESS && status != OperationResultStatus.SUCCESS) { - fail("Unexpected result status in "+result); + fail("Unexpected result status in " + result); } // WHEN @@ -1427,7 +1355,6 @@ protected void setupPhantom() throws Exception { */ @Test public void test410AssignPhoenixAccount() throws Exception { - final String TEST_NAME = "test410AssignPhoenixAccount"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1473,7 +1400,6 @@ public void test410AssignPhoenixAccount() throws Exception { */ @Test public void test412AddPhoenixToBackingStoreAndCloseTicket() throws Exception { - final String TEST_NAME = "test412AddPhoenixToBackingStoreAndCloseTicket"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1511,7 +1437,6 @@ public void test412AddPhoenixToBackingStoreAndCloseTicket() throws Exception { */ @Test public void test413PhoenixLetOperationsExpire() throws Exception { - final String TEST_NAME = "test413PhoenixLetOperationsExpire"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1548,7 +1473,6 @@ public void test413PhoenixLetOperationsExpire() throws Exception { */ @Test public void test414UnassignPhoenixAccount() throws Exception { - final String TEST_NAME = "test414UnassignPhoenixAccount"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1591,7 +1515,6 @@ public void test414UnassignPhoenixAccount() throws Exception { */ @Test public void test416PhoenixAccountUnassignCloseCase() throws Exception { - final String TEST_NAME = "test416PhoenixAccountUnassignCloseCase"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1627,7 +1550,6 @@ public void test416PhoenixAccountUnassignCloseCase() throws Exception { assertSinglePendingOperation(shadowModel, PendingOperationExecutionStatusType.COMPLETED, OperationResultStatusType.SUCCESS); - assertSteadyResources(); } @@ -1638,7 +1560,6 @@ public void test416PhoenixAccountUnassignCloseCase() throws Exception { */ @Test public void test418AssignPhoenixAccountAgain() throws Exception { - final String TEST_NAME = "test418AssignPhoenixAccountAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1674,7 +1595,7 @@ public void test418AssignPhoenixAccountAgain() throws Exception { int deadShadows = 0; int liveShadows = 0; - for (ObjectReferenceType linkRef: userAfter.asObjectable().getLinkRef()) { + for (ObjectReferenceType linkRef : userAfter.asObjectable().getLinkRef()) { try { PrismObject shadowModel = getShadowModelNoFetch(linkRef.getOid()); @@ -1689,7 +1610,7 @@ public void test418AssignPhoenixAccountAgain() throws Exception { } } catch (ObjectNotFoundException e) { - display("Shadow after", "NOT FOUND: "+linkRef.getOid()); + display("Shadow after", "NOT FOUND: " + linkRef.getOid()); } } assertEquals("Unexpected number of dead shadows", 1, deadShadows); @@ -1704,7 +1625,6 @@ protected boolean are9xxTestsEnabled() { return false; } - protected int getConcurrentTestNumberOfThreads() { return 4; } @@ -1722,15 +1642,12 @@ protected int getConcurrentTestRandomStartDelayRangeUnassign() { */ @Test public void test900SetUpRoles() throws Exception { - final String TEST_NAME = "test900SetUpRoles"; if (!are9xxTestsEnabled()) { - displaySkip(TEST_NAME); + displaySkip(); return; } // GIVEN - Task task = getTestTask(); - SystemConfigurationType systemConfiguration = getSystemConfiguration(); display("System config", systemConfiguration); ConflictResolutionActionType conflictResolutionAction = systemConfiguration.getDefaultObjectPolicyConfiguration().get(0).getConflictResolution().getAction(); @@ -1738,7 +1655,6 @@ public void test900SetUpRoles() throws Exception { fail("Wrong conflict resolution action: " + conflictResolutionAction); } - for (int i = 0; i < getConcurrentTestNumberOfThreads(); i++) { PrismObject role = parseObject(getRoleOneFile()); role.setOid(getRoleOid(i)); @@ -1767,13 +1683,11 @@ protected String getRoleInterest(int i) { return String.format("i%012d", i); } - // MID-4047, MID-4112 @Test public void test910ConcurrentRolesAssign() throws Exception { - final String TEST_NAME = "test910ConcurrentRolesAssign"; if (!are9xxTestsEnabled()) { - displaySkip(TEST_NAME); + displaySkip(); return; } @@ -1781,7 +1695,6 @@ public void test910ConcurrentRolesAssign() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); - int numberOfCasesBefore = getObjectCount(CaseType.class); PrismObject userBefore = getUser(USER_DRAKE_OID); display("user before", userBefore); assertLinks(userBefore, 0); @@ -1816,7 +1729,7 @@ public void test910ConcurrentRolesAssign() throws Exception { assertTest910ShadowRepo(shadowRepo); - Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountDrakeOid, options, task, result); display("Shadow after (model, future)", shadowModel); @@ -1826,21 +1739,21 @@ public void test910ConcurrentRolesAssign() throws Exception { protected void assertTest910ShadowRepo(PrismObject shadowRepo) throws Exception { assertShadowNotDead(shadowRepo); ObjectDeltaType addPendingDelta = null; - for (PendingOperationType pendingOperation: shadowRepo.asObjectable().getPendingOperation()) { + for (PendingOperationType pendingOperation : shadowRepo.asObjectable().getPendingOperation()) { ObjectDeltaType delta = pendingOperation.getDelta(); if (delta.getChangeType() == ChangeTypeType.ADD) { ObjectType objectToAdd = delta.getObjectToAdd(); display("Pending ADD object", objectToAdd.asPrismObject()); if (addPendingDelta != null) { - fail("More than one add pending delta found:\n"+addPendingDelta+"\n"+delta); + fail("More than one add pending delta found:\n" + addPendingDelta + "\n" + delta); } addPendingDelta = delta; } if (delta.getChangeType() == ChangeTypeType.DELETE) { - fail("Unexpected delete pending delta found:\n"+delta); + fail("Unexpected delete pending delta found:\n" + delta); } if (isActivationStatusModifyDelta(delta, ActivationStatusType.ENABLED)) { - fail("Unexpected enable pending delta found:\n"+delta); + fail("Unexpected enable pending delta found:\n" + delta); } } assertNotNull("No add pending delta", addPendingDelta); @@ -1849,9 +1762,8 @@ protected void assertTest910ShadowRepo(PrismObject shadowRepo) throw // MID-4112 @Test public void test919ConcurrentRoleUnassign() throws Exception { - final String TEST_NAME = "test919ConcurrentRoleUnassign"; if (!are9xxTestsEnabled()) { - displaySkip(TEST_NAME); + displaySkip(); return; } @@ -1859,7 +1771,6 @@ public void test919ConcurrentRoleUnassign() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); - int numberOfCasesBefore = getObjectCount(CaseType.class); PrismObject userBefore = getUser(USER_DRAKE_OID); display("user before", userBefore); assertAssignments(userBefore, getConcurrentTestNumberOfThreads()); @@ -1871,7 +1782,7 @@ public void test919ConcurrentRoleUnassign() throws Exception { ParallelTestThread[] threads = multithread( (i) -> { - display("Thread "+Thread.currentThread().getName()+" START"); + display("Thread " + Thread.currentThread().getName() + " START"); login(userAdministrator); Task localTask = getTestTask(); OperationResult localResult = localTask.getResult(); @@ -1880,7 +1791,7 @@ public void test919ConcurrentRoleUnassign() throws Exception { localResult.computeStatus(); - display("Thread "+Thread.currentThread().getName()+" DONE, result", localResult); + display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRangeUnassign()); @@ -1899,7 +1810,7 @@ public void test919ConcurrentRoleUnassign() throws Exception { PrismObject shadowModel = modelService.getObject(ShadowType.class, accountDrakeOid, null, task, result); display("Shadow after (model)", shadowModel); - Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, accountDrakeOid, options, task, result); display("Shadow after (model, future)", shadowModelFuture); @@ -1912,7 +1823,7 @@ public void test919ConcurrentRoleUnassign() throws Exception { protected void assertTest919ShadowRepo(PrismObject shadowRepo, Task task, OperationResult result) throws Exception { ObjectDeltaType deletePendingDelta = null; - for (PendingOperationType pendingOperation: shadowRepo.asObjectable().getPendingOperation()) { + for (PendingOperationType pendingOperation : shadowRepo.asObjectable().getPendingOperation()) { ObjectDeltaType delta = pendingOperation.getDelta(); if (delta.getChangeType() == ChangeTypeType.ADD) { ObjectType objectToAdd = delta.getObjectToAdd(); @@ -1920,7 +1831,7 @@ protected void assertTest919ShadowRepo(PrismObject shadowRepo, Task } if (delta.getChangeType() == ChangeTypeType.DELETE) { if (deletePendingDelta != null) { - fail("More than one delete pending delta found:\n"+deletePendingDelta+"\n"+delta); + fail("More than one delete pending delta found:\n" + deletePendingDelta + "\n" + delta); } deletePendingDelta = delta; } @@ -1932,11 +1843,11 @@ protected boolean isActivationStatusModifyDelta(ObjectDeltaType delta, Activatio if (delta.getChangeType() != ChangeTypeType.MODIFY) { return false; } - for (ItemDeltaType itemDelta: delta.getItemDelta()) { + for (ItemDeltaType itemDelta : delta.getItemDelta()) { ItemPath deltaPath = itemDelta.getPath().getItemPath(); if (SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS.equivalent(deltaPath)) { List value = itemDelta.getValue(); - PrismProperty parsedItem = (PrismProperty)(Item) + PrismProperty parsedItem = (PrismProperty) (Item) value.get(0).getParsedItem(getUserDefinition().findPropertyDefinition(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS)); ActivationStatusType status = parsedItem.getRealValue(); display("Delta status " + status, itemDelta); @@ -1953,7 +1864,8 @@ protected void assertTest919ShadowFuture(PrismObject shadowModelFutu assertShadowDead(shadowModelFuture); } - protected void assertAccountWillAfterFullNameModification(final String TEST_NAME, PendingOperationExecutionStatusType executionStage) throws Exception { + protected void assertAccountWillAfterFullNameModification( + PendingOperationExecutionStatusType executionStage) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2050,7 +1962,7 @@ protected void backingStoreAddPhoenix() throws IOException { } } - protected void assignWillRoleOne(final String TEST_NAME, String expectedFullName, PendingOperationExecutionStatusType executionStage) throws Exception { + protected void assignWillRoleOne(String expectedFullName, PendingOperationExecutionStatusType executionStage) throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2072,43 +1984,44 @@ protected void assignWillRoleOne(final String TEST_NAME, String expectedFullName accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - assertAccountWillAfterAssign(TEST_NAME, expectedFullName, executionStage); + assertAccountWillAfterAssign(expectedFullName, executionStage); } - protected void assertAccountWillAfterAssign(final String TEST_NAME, String expectedFullName, - PendingOperationExecutionStatusType propagationExecutionStage) throws Exception { + protected void assertAccountWillAfterAssign( + String expectedFullName, PendingOperationExecutionStatusType propagationExecutionStage) + throws Exception { ShadowAsserter shadowRepoAsserter = assertRepoShadow(accountWillOid) - .assertConception() - .pendingOperations() + .assertConception() + .pendingOperations() .singleOperation() - .assertId() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(getExpectedExecutionStatus(propagationExecutionStage)) - .delta() - .display() - .end() - .end() + .assertId() + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(getExpectedExecutionStatus(propagationExecutionStage)) + .delta() + .display() + .end() + .end() .end() - .attributes() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end() - .assertNoPassword(); + .assertNoPassword(); assertAttributeFromCache(shadowRepoAsserter, ATTR_FULLNAME_QNAME, expectedFullName); assertShadowActivationAdministrativeStatusFromCache(shadowRepoAsserter.getObject(), ActivationStatusType.ENABLED); - ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertConception() - .attributes() + ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertConception() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end() - .assertNoPassword() - .pendingOperations() + .assertNoPassword() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(getExpectedExecutionStatus(propagationExecutionStage)) - .end() + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(getExpectedExecutionStatus(propagationExecutionStage)) + .end() .end(); assertAttributeFromCache(shadowModelAsserter, ATTR_FULLNAME_QNAME, expectedFullName); assertShadowActivationAdministrativeStatusFromCache(shadowModelAsserter.getObject(), ActivationStatusType.ENABLED); @@ -2145,8 +2058,7 @@ protected boolean caseShouldExist(PendingOperationExecutionStatusType executionS protected abstract PendingOperationExecutionStatusType getExpectedExecutionStatus(PendingOperationExecutionStatusType executionStage); - - protected void assertAccountJackAfterAssign(final String TEST_NAME) throws Exception { + protected void assertAccountJackAfterAssign() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2182,48 +2094,45 @@ protected void assertAccountJackAfterAssign(final String TEST_NAME) throws Excep assertCaseState(jackLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - protected void assertWillAfterCreateCaseClosed(final String TEST_NAME, boolean backingStoreUpdated) throws Exception { - Task task = getTestTask(); - OperationResult result = task.getResult(); - + protected void assertWillAfterCreateCaseClosed(boolean backingStoreUpdated) throws Exception { ShadowAsserter shadowRepoAsserter = assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) - .end() + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) .end() - .attributes() + .end() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end(); assertAttributeFromCache(shadowRepoAsserter, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); assertShadowActivationAdministrativeStatusFromCache(shadowRepoAsserter, ActivationStatusType.ENABLED); ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end(); if (!supportsBackingStore() || backingStoreUpdated) { shadowRepoAsserter - .assertLife(); + .assertLife(); shadowModelAsserter - .assertLife() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertLife() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME) .end() - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) - .end() + .assertRequestTimestamp(accountWillReqestTimestampStart, accountWillReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) + .end() .end(); assertAttributeFromBackingStore(shadowModelAsserter, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelAsserter); @@ -2231,10 +2140,10 @@ protected void assertWillAfterCreateCaseClosed(final String TEST_NAME, boolean b } else { shadowRepoAsserter - .assertGestation(); + .assertGestation(); shadowModelAsserter - .assertGestation(); + .assertGestation(); } assertCaseState(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); @@ -2242,20 +2151,20 @@ protected void assertWillAfterCreateCaseClosed(final String TEST_NAME, boolean b protected void assertWillUnassignedFuture(ShadowAsserter shadowModelAsserterFuture, boolean assertPassword) { shadowModelAsserterFuture - .assertName(USER_WILL_NAME); + .assertName(USER_WILL_NAME); assertUnassignedFuture(shadowModelAsserterFuture, assertPassword); } protected void assertUnassignedFuture(ShadowAsserter shadowModelAsserterFuture, boolean assertPassword) { shadowModelAsserterFuture - .assertDead(); + .assertDead(); if (assertPassword) { assertShadowPassword(shadowModelAsserterFuture); } } - - protected void assertAttribute(PrismObject shadow, QName attrName, T... expectedValues) { + protected void assertAttribute( + PrismObject shadow, QName attrName, T... expectedValues) { assertAttribute(shadow.asObjectable(), attrName, expectedValues); } @@ -2317,14 +2226,17 @@ protected void assertShadowPassword(PrismObject shadow) { } private void assertManual(AbstractWriteCapabilityType cap) { - assertEquals("Manual flag not set in capability "+cap, Boolean.TRUE, cap.isManual()); + assertEquals("Manual flag not set in capability " + cap, Boolean.TRUE, cap.isManual()); } protected void cleanupUser(String userOid, String username, String accountOid) throws Exception { // nothing to do here } - protected void assertCase(String oid, String expectedState, PendingOperationExecutionStatusType executionStage) throws ObjectNotFoundException, SchemaException { + @UnusedTestElement + protected void assertCase( + String oid, String expectedState, PendingOperationExecutionStatusType executionStage) + throws ObjectNotFoundException, SchemaException { if (caseShouldExist(executionStage)) { assertCaseState(oid, expectedState); } @@ -2341,7 +2253,7 @@ protected void runPropagation(OperationResultStatusType expectedStatus) throws E @Override protected void rememberSteadyResources() { super.rememberSteadyResources(); - OperationResult result = new OperationResult("rememberSteadyResources"); + OperationResult result = createOperationResult("rememberSteadyResources"); try { lastResourceVersion = repositoryService.getVersion(ResourceType.class, getResourceOid(), result); } catch (ObjectNotFoundException | SchemaException e) { @@ -2352,23 +2264,24 @@ protected void rememberSteadyResources() { @Override protected void assertSteadyResources() { super.assertSteadyResources(); - String currentResourceVersion; try { - OperationResult result = new OperationResult("assertSteadyResources"); - currentResourceVersion = repositoryService.getVersion(ResourceType.class, getResourceOid(), result); + OperationResult result = createOperationResult("assertSteadyResources"); + String currentResourceVersion = + repositoryService.getVersion(ResourceType.class, getResourceOid(), result); + assertEquals("Resource version mismatch", lastResourceVersion, currentResourceVersion); } catch (ObjectNotFoundException | SchemaException e) { throw new RuntimeException(e.getMessage(), e); } - assertEquals("Resource version mismatch", lastResourceVersion, currentResourceVersion); } + @UnusedTestElement protected void assertHasModification(ObjectDeltaType deltaType, ItemPath itemPath) { - for (ItemDeltaType itemDelta: deltaType.getItemDelta()) { + for (ItemDeltaType itemDelta : deltaType.getItemDelta()) { if (itemPath.equivalent(itemDelta.getPath().getItemPath())) { return; } } - fail("No modification for "+itemPath+" in delta"); + fail("No modification for " + itemPath + " in delta"); } protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvBackingStore.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvBackingStore.java index d200ab9d667..76995016c27 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvBackingStore.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvBackingStore.java @@ -20,32 +20,25 @@ import org.apache.commons.lang.StringUtils; import com.evolveum.midpoint.test.IntegrationTestTools; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; /** * @author semancik - * */ public class CsvBackingStore implements BackingStore { public static final File CSV_SOURCE_FILE = new File(AbstractManualResourceTest.TEST_DIR, "semi-manual.csv"); public static final File CSV_TARGET_FILE = new File("target/semi-manual.csv"); - private static final Trace LOGGER = TraceManager.getTrace(CsvBackingStore.class); - private final File sourceFile; private final File targetFile; public CsvBackingStore() { - super(); this.sourceFile = CSV_SOURCE_FILE; this.targetFile = CSV_TARGET_FILE; } public CsvBackingStore(File sourceFile, File targetFile) { - super(); this.sourceFile = sourceFile; this.targetFile = targetFile; } @@ -57,14 +50,14 @@ public void initialize() throws IOException { @Override public void provisionWill(String interest) throws IOException { - appendToCsv(new String[]{ + appendToCsv(new String[] { AbstractManualResourceTest.USER_WILL_NAME, AbstractManualResourceTest.USER_WILL_FULL_NAME, AbstractManualResourceTest.ACCOUNT_WILL_DESCRIPTION_MANUAL, interest, "false", AbstractManualResourceTest.USER_WILL_PASSWORD_OLD - }); + }); } @Override @@ -76,14 +69,14 @@ public void updateWill(String newFullName, String interest, ActivationStatusType } else { disabled = "true"; } - replaceInCsv(new String[]{ + replaceInCsv(new String[] { AbstractManualResourceTest.USER_WILL_NAME, newFullName, AbstractManualResourceTest.ACCOUNT_WILL_DESCRIPTION_MANUAL, interest, disabled, password - }); + }); } @Override @@ -91,17 +84,16 @@ public void deprovisionWill() throws IOException { deprovisionInCsv(AbstractManualResourceTest.USER_WILL_NAME); } - @Override public void addJack() throws IOException { - appendToCsv(new String[]{ + appendToCsv(new String[] { AbstractManualResourceTest.USER_JACK_USERNAME, AbstractManualResourceTest.USER_JACK_FULL_NAME, AbstractManualResourceTest.ACCOUNT_JACK_DESCRIPTION_MANUAL, "", "false", AbstractManualResourceTest.USER_JACK_PASSWORD_OLD - }); + }); } @Override @@ -111,7 +103,7 @@ public void deleteJack() throws IOException { @Override public void addPhantom() throws IOException { - appendToCsv(new String[]{ + appendToCsv(new String[] { AbstractManualResourceTest.USER_PHANTOM_USERNAME, // Wrong fullname here ... by purpose. We wonder whether reconciliation fixes this. AbstractManualResourceTest.USER_PHANTOM_FULL_NAME_WRONG, @@ -119,22 +111,21 @@ public void addPhantom() throws IOException { "", "false", AbstractManualResourceTest.ACCOUNT_PHANTOM_PASSWORD_MANUAL - }); + }); } @Override public void addPhoenix() throws IOException { - appendToCsv(new String[]{ + appendToCsv(new String[] { AbstractManualResourceTest.USER_PHOENIX_USERNAME, AbstractManualResourceTest.USER_PHOENIX_FULL_NAME, AbstractManualResourceTest.ACCOUNT_PHOENIX_DESCRIPTION_MANUAL, "", "false", AbstractManualResourceTest.ACCOUNT_PHOENIX_PASSWORD_MANUAL - }); + }); } - @Override public void deleteAccount(String username) throws IOException { deleteInCsv(username); @@ -152,10 +143,9 @@ protected void disableInCsv(String username) throws IOException { protected String[] readFromCsv(String username) throws IOException { List lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); + for (String line : lines) { String[] cols = line.split(","); - if (cols[0].matches("\""+username+"\"")) { + if (cols[0].matches("\"" + username + "\"")) { return unescape(cols); } } @@ -183,13 +173,13 @@ protected void replaceInCsv(String[] data) throws IOException { for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] cols = line.split(","); - if (cols[0].matches("\""+data[0]+"\"")) { + if (cols[0].matches("\"" + data[0] + "\"")) { lines.set(i, formatCsvLine(data)); found = true; } } if (!found) { - throw new IllegalStateException("Not found in CSV: "+data[0]); + throw new IllegalStateException("Not found in CSV: " + data[0]); } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); @@ -201,7 +191,7 @@ protected void deleteInCsv(String username) throws IOException { while (iterator.hasNext()) { String line = iterator.next(); String[] cols = line.split(","); - if (cols[0].matches("\""+username+"\"")) { + if (cols[0].matches("\"" + username + "\"")) { iterator.remove(); } } @@ -210,7 +200,7 @@ protected void deleteInCsv(String username) throws IOException { } private String formatCsvLine(String[] data) { - return Arrays.stream(data).map(s -> "\""+s+"\"").collect(Collectors.joining(",")) + "\n"; + return Arrays.stream(data).map(s -> "\"" + s + "\"").collect(Collectors.joining(",")) + "\n"; } @Override @@ -224,7 +214,7 @@ protected String dumpCsv() throws IOException { @Override public String toString() { - return this.getClass().getSimpleName()+"(" + targetFile + ")"; + return this.getClass().getSimpleName() + "(" + targetFile + ")"; } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvDisablingBackingStore.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvDisablingBackingStore.java index 546122b1cba..ee8d84c5fde 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvDisablingBackingStore.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/CsvDisablingBackingStore.java @@ -9,17 +9,12 @@ import java.io.File; import java.io.IOException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; - /** * @author semancik * */ public class CsvDisablingBackingStore extends CsvBackingStore { - private static final Trace LOGGER = TraceManager.getTrace(CsvDisablingBackingStore.class); - public CsvDisablingBackingStore() { super(); } @@ -31,6 +26,4 @@ public CsvDisablingBackingStore(File sourceFile, File targetFile) { protected void deprovisionInCsv(String username) throws IOException { disableInCsv(username); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/DummyItsmIntegrationConnectorInstance.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/DummyItsmIntegrationConnectorInstance.java index a2af81c6448..b3faafbb2d9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/DummyItsmIntegrationConnectorInstance.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/DummyItsmIntegrationConnectorInstance.java @@ -104,7 +104,7 @@ protected String createTicketAdd(PrismObject object, Opera protected String createTicketModify(ObjectClassComplexTypeDefinition objectClass, PrismObject shadow, Collection> identifiers, String resourceOid, Collection changes, OperationResult result) - throws ObjectNotFoundException, CommunicationException, GenericFrameworkException, + throws CommunicationException, GenericFrameworkException, SchemaException, ObjectAlreadyExistsException, ConfigurationException { DummyItsm itsm = DummyItsm.getInstance(); String identifier; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestDummyItsmIntegration.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestDummyItsmIntegration.java index 7c530853a82..0fe64d844f9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestDummyItsmIntegration.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestDummyItsmIntegration.java @@ -31,8 +31,6 @@ import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; @@ -55,8 +53,6 @@ public class TestDummyItsmIntegration extends AbstractConfiguredModelIntegration public static final QName RESOURCE_ACCOUNT_OBJECTCLASS = new QName(MidPointConstants.NS_RI, "AccountObjectClass"); - private static final Trace LOGGER = TraceManager.getTrace(TestDummyItsmIntegration.class); - protected static final String NS_MANUAL_CONF = "http://midpoint.evolveum.com/xml/ns/public/connector/builtin-1/bundle/com.evolveum.midpoint.model.intest.manual/DummyItsmIntegrationConnector"; protected static final File RESOURCE_DUMMY_ITSM_FILE = new File(TEST_DIR, "resource-dummy-itsm.xml"); @@ -75,7 +71,6 @@ public class TestDummyItsmIntegration extends AbstractConfiguredModelIntegration protected static final QName ATTR_DESCRIPTION_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DESCRIPTION); protected PrismObject resource; - protected ResourceType resourceType; private String jackLastTicketIdentifier; @@ -97,10 +92,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - - OperationResult result = new OperationResult(TestDummyItsmIntegration.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); ResourceType repoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_ITSM_OID, null, result).asObjectable(); @@ -119,7 +111,6 @@ public void test000Sanity() throws Exception { @Test public void test012TestConnection() throws Exception { - final String TEST_NAME = "test012TestConnection"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -147,7 +138,6 @@ public void test012TestConnection() throws Exception { */ @Test public void test100AssignAccountToJack() throws Exception { - final String TEST_NAME = "test100AssignAccountToJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -176,7 +166,6 @@ public void test100AssignAccountToJack() throws Exception { @Test public void test102CloseTicketAndRecomputeJack() throws Exception { - final String TEST_NAME = "test102CloseTicketAndRecomputeJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -197,12 +186,11 @@ public void test102CloseTicketAndRecomputeJack() throws Exception { PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", shadowRepo); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, PendingOperationExecutionStatusType.COMPLETED, OperationResultStatusType.SUCCESS); + assertSinglePendingOperation(shadowRepo, PendingOperationExecutionStatusType.COMPLETED, OperationResultStatusType.SUCCESS); } @Test public void test104UnassignAccountFromJack() throws Exception { - final String TEST_NAME = "test104UnassignAccountFromJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -232,7 +220,6 @@ public void test104UnassignAccountFromJack() throws Exception { @Test public void test108CloseTicketAndRecomputeJack() throws Exception { - final String TEST_NAME = "test108CloseTicketAndRecomputeJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -268,7 +255,6 @@ public void test108CloseTicketAndRecomputeJack() throws Exception { */ @Test public void test109LetItExpire() throws Exception { - final String TEST_NAME = "test109LetItExpire"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -292,7 +278,6 @@ public void test109LetItExpire() throws Exception { */ @Test public void test110AssignItsmAccountToJackCommunicationError() throws Exception { - final String TEST_NAME = "test110AssignItsmAccountToJackCommunicationError"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -327,7 +312,6 @@ public void test110AssignItsmAccountToJackCommunicationError() throws Exception @Test public void test111ReconcileJackFixed() throws Exception { - final String TEST_NAME = "test111ReconcileJackFixed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -371,7 +355,6 @@ public void test111ReconcileJackFixed() throws Exception { @Test public void test112CloseTicketAndRecomputeJackCommunicationError() throws Exception { - final String TEST_NAME = "test112CloseTicketAndRecomputeJackCommunicationError"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -408,7 +391,6 @@ public void test112CloseTicketAndRecomputeJackCommunicationError() throws Except @Test public void test113RecomputeJackFixed() throws Exception { - final String TEST_NAME = "test113RecomputeJackFixed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -442,7 +424,6 @@ public void test113RecomputeJackFixed() throws Exception { @Test public void test114UnassignAccountFromJackCommunicationError() throws Exception { - final String TEST_NAME = "test114UnassignAccountFromJackCommunicationError"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -494,7 +475,6 @@ public void test114UnassignAccountFromJackCommunicationError() throws Exception @Test public void test115ReconcileJackFixed() throws Exception { - final String TEST_NAME = "test115ReconcileJackFixed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -538,7 +518,6 @@ public void test115ReconcileJackFixed() throws Exception { @Test public void test117CloseTicketAndRecomputeJackCommunicationError() throws Exception { - final String TEST_NAME = "test117CloseTicketAndRecomputeJackCommunicationError"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -575,7 +554,6 @@ public void test117CloseTicketAndRecomputeJackCommunicationError() throws Except @Test public void test118RecomputeJackFixed() throws Exception { - final String TEST_NAME = "test118RecomputeJackFixed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -616,7 +594,6 @@ public void test118RecomputeJackFixed() throws Exception { */ @Test public void test119LetItExpire() throws Exception { - final String TEST_NAME = "test119LetItExpire"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java index bb63a51ae4b..0565135974f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java @@ -6,14 +6,10 @@ */ package com.evolveum.midpoint.model.intest.manual; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; -import javax.xml.namespace.QName; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -24,35 +20,23 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.test.asserter.UserAsserter; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManual extends AbstractDirectManualResourceTest { - private static final Trace LOGGER = TraceManager.getTrace(TestSemiManual.class); - protected static final String ATTR_DISABLED = "disabled"; - protected static final QName ATTR_DISABLED_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DISABLED); @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -116,7 +100,6 @@ protected int getNumberOfAccountAttributeDefinitions() { */ @Test public void test700AssignAccountJackExisting() throws Exception { - final String TEST_NAME = "test700AssignAccountJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -175,7 +158,6 @@ public void test700AssignAccountJackExisting() throws Exception { */ @Test public void test710UnassignAccountJack() throws Exception { - final String TEST_NAME = "test710UnassignAccountJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -230,7 +212,6 @@ public void test710UnassignAccountJack() throws Exception { */ @Test public void test712CloseCaseAndRecomputeJack() throws Exception { - final String TEST_NAME = "test712CloseCaseAndRecomputeJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -254,27 +235,27 @@ public void test712CloseCaseAndRecomputeJack() throws Exception { accountJackCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); ShadowAsserter shadowRepoAsserter = assertRepoShadow(accountJackOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountJackReqestTimestampStart, accountJackReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd) + .assertRequestTimestamp(accountJackReqestTimestampStart, accountJackReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd) .end() - .end(); + .end(); assertUnassignedShadow(shadowRepoAsserter, true, null); ShadowAsserter shadowModelAsserter = assertModelShadow(accountJackOid) - .assertName(USER_JACK_USERNAME) - .assertKind(ShadowKindType.ACCOUNT) - .pendingOperations() + .assertName(USER_JACK_USERNAME) + .assertKind(ShadowKindType.ACCOUNT) + .pendingOperations() .singleOperation() - .assertRequestTimestamp(accountJackReqestTimestampStart, accountJackReqestTimestampEnd) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd) + .assertRequestTimestamp(accountJackReqestTimestampStart, accountJackReqestTimestampEnd) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd) .end() - .end(); + .end(); assertUnassignedShadow(shadowModelAsserter, true, ActivationStatusType.DISABLED); assertUnassignedFuture(assertModelShadowFuture(accountJackOid), false); @@ -287,7 +268,6 @@ public void test712CloseCaseAndRecomputeJack() throws Exception { */ @Test public void test717RecomputeJackAfter130min() throws Exception { - final String TEST_NAME = "test717RecomputeJackAfter130min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -316,8 +296,6 @@ public void test717RecomputeJackAfter130min() throws Exception { */ @Test public void test719CleanUp() throws Exception { - final String TEST_NAME = "test719CleanUp"; - cleanupUser(USER_JACK_OID, USER_JACK_USERNAME, accountJackOid); } @@ -325,7 +303,7 @@ public void test719CleanUp() throws Exception { protected void assertShadowPassword(PrismObject shadow) { // CSV password is readable PrismProperty passValProp = shadow.findProperty(SchemaConstants.PATH_PASSWORD_VALUE); - assertNotNull("No password value property in "+shadow+": "+passValProp, passValProp); + assertNotNull("No password value property in " + shadow + ": " + passValProp, passValProp); } @Override diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisableSlowProposed.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisableSlowProposed.java index 53859047ac2..b2ec2814f2c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisableSlowProposed.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisableSlowProposed.java @@ -19,29 +19,21 @@ import com.evolveum.midpoint.provisioning.ucf.impl.builtin.ManualConnectorInstance; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionActionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ObjectType; /** * @author Radovan Semancik - * + *

* THIS TEST IS DISABLED MID-4166 */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManualDisableSlowProposed extends TestSemiManualDisable { - private static final Trace LOGGER = TraceManager.getTrace(TestSemiManualDisableSlowProposed.class); - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -120,7 +112,7 @@ protected void initManualConnector() { @Override protected void assertTest919ShadowRepo(PrismObject shadowRepo, Task task, OperationResult result) throws Exception { ObjectDeltaType disablePendingDelta = null; - for (PendingOperationType pendingOperation: shadowRepo.asObjectable().getPendingOperation()) { + for (PendingOperationType pendingOperation : shadowRepo.asObjectable().getPendingOperation()) { ObjectDeltaType delta = pendingOperation.getDelta(); if (delta.getChangeType() == ChangeTypeType.ADD) { ObjectType objectToAdd = delta.getObjectToAdd(); @@ -128,15 +120,15 @@ protected void assertTest919ShadowRepo(PrismObject shadowRepo, Task } if (isActivationStatusModifyDelta(delta, ActivationStatusType.DISABLED)) { if (disablePendingDelta != null) { - fail("More than one disable pending delta found:\n"+disablePendingDelta+"\n"+delta); + fail("More than one disable pending delta found:\n" + disablePendingDelta + "\n" + delta); } disablePendingDelta = delta; } if (isActivationStatusModifyDelta(delta, ActivationStatusType.ENABLED)) { - fail("Unexpected enable pending delta found:\n"+delta); + fail("Unexpected enable pending delta found:\n" + delta); } if (delta.getChangeType() == ChangeTypeType.DELETE) { - fail("Unexpected delete pending delta found:\n"+disablePendingDelta+"\n"+delta); + fail("Unexpected delete pending delta found:\n" + disablePendingDelta + "\n" + delta); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGroupingProposed.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGroupingProposed.java index bbff1af65b9..01b5789d324 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGroupingProposed.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGroupingProposed.java @@ -10,7 +10,6 @@ import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; import java.io.File; @@ -52,9 +51,7 @@ public class TestSemiManualGroupingProposed extends TestSemiManualGrouping { private static final String USER_BIGMOUTH_NAME = "BIGMOUTH"; private static final String USER_BIGMOUTH_FULLNAME = "Shouty Bigmouth"; - private String userBigmouthOid; private String accountBigmouthOid; - private String bigmouthLastCaseOid; @Override protected File getResourceFile() { @@ -75,8 +72,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test020ResourcesSanity() throws Exception { - final String TEST_NAME = "test020ResourcesSanity"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -87,14 +82,15 @@ public void test020ResourcesSanity() throws Exception { ObjectQuery query = prismContext.queryFor(ResourceType.class) .item("extension","provisioning").eq("propagated") .build(); - SearchResultList> propagatedResources = repositoryService.searchObjects(ResourceType.class, query, null, result); + SearchResultList> propagatedResources = + repositoryService.searchObjects(ResourceType.class, query, null, result); display("Propagated resources", propagatedResources.size() + ": " + propagatedResources); assertEquals("Unexpected number of propagated resources", 1, propagatedResources.size()); } @Override protected void assertNewPropagationTask() throws Exception { - OperationResult result = new OperationResult("assertNewPropagationTask"); + OperationResult result = createOperationResult("assertNewPropagationTask"); PrismObject propTask = repositoryService.getObject(TaskType.class, getPropagationTaskOid(), null, result); display("Propagation task (new)", propTask); SearchFilterType filterType = propTask.asObjectable().getObjectRef().getFilter(); @@ -118,13 +114,12 @@ protected void assertFinishedPropagationTask(Task finishedTask, OperationResultS */ @Test public void test500AssignBigmouthRoleOne() throws Exception { - final String TEST_NAME = "test500AssignBigmouthRoleOne"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = createUser(USER_BIGMOUTH_NAME, USER_BIGMOUTH_FULLNAME, true); - userBigmouthOid = addObject(userBefore); + String userBigmouthOid = addObject(userBefore); display("User before", userBefore); // WHEN @@ -134,7 +129,7 @@ public void test500AssignBigmouthRoleOne() throws Exception { // THEN then(); display("result", result); - bigmouthLastCaseOid = assertInProgress(result); + assertInProgress(result); PrismObject userAfter = getUser(userBigmouthOid); display("User after", userAfter); @@ -166,7 +161,7 @@ public void test500AssignBigmouthRoleOne() throws Exception { assertShadowActivationAdministrativeStatusFromCache(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, false); assertNoShadowPassword(shadowModel); - PendingOperationType pendingOperationType = assertSinglePendingOperation(shadowModel, null, null, executionStage); + assertSinglePendingOperation(shadowModel, null, null, executionStage); } /** @@ -174,7 +169,6 @@ public void test500AssignBigmouthRoleOne() throws Exception { */ @Test public void test502RunPropagation() throws Exception { - final String TEST_NAME = "test502RunPropagation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java index bca2d3b166e..bf7ac4a5735 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java @@ -19,26 +19,22 @@ import com.evolveum.midpoint.repo.cache.RepositoryCache; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; /** * Tests a slow semi manual resource with the use of proposed shadows. * The resource is "slow" in a way that it takes approx. a second to process a ticket. * This may cause all sorts of race conditions. - * + *

* THIS TEST IS DISABLED MID-4166 * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManualSlowProposed extends TestSemiManual { - private static final Trace LOGGER = TraceManager.getTrace(TestSemiManualSlowProposed.class); - - @Autowired(required = true) + @Autowired @Qualifier("cacheRepositoryService") private RepositoryCache repositoryCache; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiConnectorResources.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiConnectorResources.java index 14c0d929d51..9e0e8849740 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiConnectorResources.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiConnectorResources.java @@ -6,40 +6,35 @@ */ package com.evolveum.midpoint.model.intest.multi; -import com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.DummyResourceContoller; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; -import java.io.File; - -import static org.testng.AssertJUnit.*; +import com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.util.TestUtil; /** * Test resources that have several connectors. - * + *

* MID-5921 * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMultiConnectorResources extends AbstractConfiguredModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/multi-connector"); - private static final Trace LOGGER = TraceManager.getTrace(TestMultiConnectorResources.class); - // Black dummy resource for testing tolerant attributes protected static final File RESOURCE_DUMMY_OPALINE_FILE = new File(TEST_DIR, "resource-dummy-opaline.xml"); protected static final String RESOURCE_DUMMY_OPALINE_OID = "d4a2a030-0a1c-11ea-b61c-67d35cfea30f"; @@ -49,7 +44,6 @@ public class TestMultiConnectorResources extends AbstractConfiguredModelIntegrat private static final String CONF_USELESS_OPALINE = "USEless-opaline"; private static final String CONF_USELESS_SCRIPT = "USEless-script"; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -67,8 +61,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - // GIVEN Task task = getTestTask(); @@ -86,8 +78,6 @@ public void test000Sanity() throws Exception { @Test public void test100JackAssignDummyOpaline() throws Exception { - final String TEST_NAME = "test100JackAssignDummyOpaline"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -100,9 +90,9 @@ public void test100JackAssignDummyOpaline() throws Exception { assertUserAfter(USER_JACK_OID) .singleLink() - .target() - .assertResource(RESOURCE_DUMMY_OPALINE_OID) - .assertName(ACCOUNT_JACK_DUMMY_USERNAME); + .target() + .assertResource(RESOURCE_DUMMY_OPALINE_OID) + .assertName(ACCOUNT_JACK_DUMMY_USERNAME); assertDummyAccountByUsername(RESOURCE_DUMMY_OPALINE_NAME, ACCOUNT_JACK_DUMMY_USERNAME) .assertFullName(USER_JACK_FULL_NAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java index 8811e89d649..0ea5a788306 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java @@ -859,7 +859,7 @@ public void test229JackUnassignDummyBeigeAndDefault() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); // CLEANUP - make sure we have clean slate for next tests - displayCleanup(contextName()); + displayCleanup(); forceDeleteShadow(deadShadowOid); assertNoShadow(deadShadowOid); @@ -2455,7 +2455,7 @@ public void test440DavidAndGoliathAssignRoleAndCreateUserInOneStep() throws Exce deltas.add(delta); modelService.executeChanges(deltas, null, task, result); - OperationResult deleteResult = new OperationResult("Check if user was deleted properly."); + OperationResult deleteResult = createOperationResult("Check if user was deleted properly."); try { repositoryService.getObject(UserType.class, userWorld.getOid(), null, deleteResult); } catch (ObjectNotFoundException ex) { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java index 72fff14fd9f..b33fd62a8e9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java @@ -1280,7 +1280,7 @@ public void test528UnassignResourceEbony() throws Exception { assertDummyScripts(RESOURCE_DUMMY_EBONY_NAME, "delete/after", DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); // CLEANUP - displayCleanup(TEST_NAME); + displayCleanup(); forceDeleteShadow(shadowOid); assertUserAfter(USER_GUYBRUSH_OID) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java index 568bc8c4301..1f3c3297718 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java @@ -163,7 +163,7 @@ public void test345AssignMonkeyAccountBlue() throws Exception { assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, USER_THREE_HEADED_MONKEY_NAME); // CLEANUP - displayCleanup(contextName()); + displayCleanup(); unassignAccountFromUser(USER_THREE_HEADED_MONKEY_OID, RESOURCE_DUMMY_BLUE_OID, null, task, result); @@ -210,7 +210,7 @@ public void test347AssignMonkeyAccountYellow() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_BLUE_NAME, USER_THREE_HEADED_MONKEY_NAME); // CLEANUP - displayCleanup(contextName()); + displayCleanup(); unassignAccountFromUser(USER_THREE_HEADED_MONKEY_OID, RESOURCE_DUMMY_YELLOW_OID, null, task, result); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java index 47309a9d71e..d11a0ac5367 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java @@ -6,6 +6,25 @@ */ package com.evolveum.midpoint.model.intest.scripting; +import static java.util.Collections.singleton; +import static org.apache.commons.collections4.CollectionUtils.emptyIfNull; +import static org.testng.AssertJUnit.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; +import javax.xml.bind.JAXBException; +import javax.xml.namespace.QName; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; +import org.testng.collections.Sets; + import com.evolveum.midpoint.common.LoggingConfigurationManager; import com.evolveum.midpoint.model.api.ModelPublicConstants; import com.evolveum.midpoint.model.api.PipelineItem; @@ -38,30 +57,11 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; -import org.testng.collections.Sets; - -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; - -import static java.util.Collections.singleton; -import static org.apache.commons.collections4.CollectionUtils.emptyIfNull; -import static org.testng.AssertJUnit.*; /** * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScriptingBasic extends AbstractInitializedModelIntegrationTest { @@ -69,7 +69,6 @@ public class TestScriptingBasic extends AbstractInitializedModelIntegrationTest public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); - private static final String DOT_CLASS = TestScriptingBasic.class.getName() + "."; private static final File LOG_FILE = new File(TEST_DIR, "log.xml"); private static final File SEARCH_FOR_USERS_FILE = new File(TEST_DIR, "search-for-users.xml"); private static final File SEARCH_FOR_USERS_WITH_EXPRESSIONS_FILE = new File(TEST_DIR, "search-for-users-with-expressions.xml"); @@ -146,8 +145,6 @@ protected File getSystemConfigurationFile() { @Test public void test100EmptySequence() throws Exception { - final String TEST_NAME = "test100EmptySequence"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -165,8 +162,6 @@ public void test100EmptySequence() throws Exception { @Test public void test110EmptyPipeline() throws Exception { - final String TEST_NAME = "test110EmptyPipeline"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -184,10 +179,8 @@ public void test110EmptyPipeline() throws Exception { @Test public void test112Echo() throws Exception { - final String TEST_NAME = "test112Echo"; - // GIVEN - Task task = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ExecuteScriptType executeScript = parseRealValue(ECHO_FILE); @@ -203,11 +196,8 @@ public void test112Echo() throws Exception { // TODO check correct serialization } - @Test public void test120Log() throws Exception { - final String TEST_NAME = "test120Log"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -239,8 +229,6 @@ private T parseRealValue(File file) throws IOException, SchemaException { @Test public void test200SearchUser() throws Exception { - final String TEST_NAME = "test200SearchUser"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -254,13 +242,10 @@ public void test200SearchUser() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); assertEquals(2, output.getFinalOutput().getData().size()); - //assertEquals("administrator", ((PrismObject) output.getData().get(0)).asObjectable().getName().getOrig()); } @Test public void test202SearchUserWithExpressions() throws Exception { - final String TEST_NAME = "test202SearchUserWithExpressions"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -285,8 +270,6 @@ public void test202SearchUserWithExpressions() throws Exception { @Test public void test205SearchForResources() throws Exception { - final String TEST_NAME = "test205SearchForResources"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -304,8 +287,6 @@ public void test205SearchForResources() throws Exception { @Test public void test206SearchForRoles() throws Exception { - final String TEST_NAME = "test206SearchForRoles"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -318,13 +299,10 @@ public void test206SearchForRoles() throws Exception { dumpOutput(output, result); result.computeStatus(); TestUtil.assertSuccess(result); - //assertEquals(9, output.getData().size()); } @Test public void test210SearchForShadows() throws Exception { - final String TEST_NAME = "test210SearchForShadows"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -343,8 +321,6 @@ public void test210SearchForShadows() throws Exception { @Test public void test215SearchForShadowsNoFetch() throws Exception { - final String TEST_NAME = "test215SearchForShadowsNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -363,8 +339,6 @@ public void test215SearchForShadowsNoFetch() throws Exception { @Test public void test220SearchForUsersAccounts() throws Exception { - final String TEST_NAME = "test220SearchForUsersAccounts"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -383,8 +357,6 @@ public void test220SearchForUsersAccounts() throws Exception { @Test public void test225SearchForUsersAccountsNoFetch() throws Exception { - final String TEST_NAME = "test225SearchForUsersAccountsNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -403,8 +375,6 @@ public void test225SearchForUsersAccountsNoFetch() throws Exception { @Test public void test300DisableJack() throws Exception { - final String TEST_NAME = "test300DisableJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -424,8 +394,6 @@ public void test300DisableJack() throws Exception { @Test public void test310EnableJack() throws Exception { - final String TEST_NAME = "test310EnableJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -445,8 +413,6 @@ public void test310EnableJack() throws Exception { @Test public void test320DeleteAndAddJack() throws Exception { - final String TEST_NAME = "test320DeleteAndAddJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -466,8 +432,6 @@ public void test320DeleteAndAddJack() throws Exception { @Test public void test330ModifyJack() throws Exception { - final String TEST_NAME = "test330ModifyJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -487,8 +451,6 @@ public void test330ModifyJack() throws Exception { @Test public void test340ModifyJackBack() throws Exception { - final String TEST_NAME = "test340ModifyJackBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -508,8 +470,6 @@ public void test340ModifyJackBack() throws Exception { @Test public void test350RecomputeJack() throws Exception { - final String TEST_NAME = "test350RecomputeJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -528,8 +488,6 @@ public void test350RecomputeJack() throws Exception { @Test public void test360AssignToJack() throws Exception { - final String TEST_NAME = "test360AssignToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -552,10 +510,8 @@ public void test360AssignToJack() throws Exception { @Test public void test370AssignToJackInBackground() throws Exception { - final String TEST_NAME = "test370AssignToJackInBackground"; - // GIVEN - OperationResult result = new OperationResult(DOT_CLASS + TEST_NAME); + OperationResult result = getTestOperationResult(); PrismProperty expression = parseAnyData(ASSIGN_TO_JACK_2_FILE); // WHEN @@ -576,10 +532,8 @@ public void test370AssignToJackInBackground() throws Exception { @Deprecated @Test public void test380DisableJackInBackgroundSimple() throws Exception { - final String TEST_NAME = "test380DisableJackInBackgroundSimple"; - // GIVEN - OperationResult result = new OperationResult(DOT_CLASS + TEST_NAME); + OperationResult result = getTestOperationResult(); // WHEN Task task = taskManager.createTaskInstance(); @@ -601,8 +555,6 @@ public void test380DisableJackInBackgroundSimple() throws Exception { @Test public void test390AssignToWill() throws Exception { - final String TEST_NAME = "test390AssignToWill"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -623,8 +575,6 @@ public void test390AssignToWill() throws Exception { @Test public void test391UnassignFromWill() throws Exception { - final String TEST_NAME = "test391UnassignFromJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -647,8 +597,6 @@ public void test391UnassignFromWill() throws Exception { @Test public void test392UnassignFromWill2() throws Exception { - final String TEST_NAME = "test392UnassignFromWill2"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -671,8 +619,6 @@ public void test392UnassignFromWill2() throws Exception { @Test public void test393UnassignFromWill3() throws Exception { - final String TEST_NAME = "test393UnassignFromWill3"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -695,8 +641,6 @@ public void test393UnassignFromWill3() throws Exception { @Test public void test394AssignToWill2() throws Exception { - final String TEST_NAME = "test394AssignToWill2"; - // GIVEN QName customRelation = new QName("http://midpoint.evolveum.com/xml/ns/samples/piracy", "piracy:captain"); @@ -712,7 +656,7 @@ public void test394AssignToWill2() throws Exception { Collection modifications = new ArrayList<>(); ContainerDelta deleteDelta = prismContext.deltaFactory().container().createModificationReplace(SystemConfigurationType.F_ROLE_MANAGEMENT, SystemConfigurationType.class, oldValue.clone()); - ((Collection)modifications).add(deleteDelta); + ((Collection) modifications).add(deleteDelta); modifySystemObjectInRepo(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, result); @@ -731,18 +675,11 @@ public void test394AssignToWill2() throws Exception { @Test public void test400PurgeSchema() throws Exception { - final String TEST_NAME = "test400PurgeSchema"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); PrismProperty expression = parseAnyData(PURGE_DUMMY_BLACK_SCHEMA_FILE); -// ResourceType dummy = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_BLACK_OID, null, task, result).asObjectable(); -// IntegrationTestTools.display("dummy resource before purge schema", dummy.asPrismObject()); -// IntegrationTestTools.display("elements: " + dummy.getSchema().getDefinition().getAny().get(0).getElementsByTagName("*").getLength()); -// IntegrationTestTools.display("schema as XML: " + DOMUtil.printDom(dummy.getSchema().getDefinition().getAny().get(0))); - // WHEN ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result); @@ -752,21 +689,13 @@ public void test400PurgeSchema() throws Exception { TestUtil.assertSuccess(result); assertEquals(1, output.getFinalOutput().getData().size()); -// dummy = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_BLACK_OID, null, result).asObjectable(); -// IntegrationTestTools.display("dummy resource from repo", dummy.asPrismObject()); -// IntegrationTestTools.display("elements: " + dummy.getSchema().getDefinition().getAny().get(0).getElementsByTagName("*").getLength()); -// IntegrationTestTools.display("schema as XML: " + DOMUtil.printDom(dummy.getSchema().getDefinition().getAny().get(0))); - //AssertJUnit.assertNull("Schema is still present", dummy.getSchema()); // actually, schema gets downloaded just after purging it assertEquals("Purged schema information from resource:10000000-0000-0000-0000-000000000305(Dummy Resource Black)\n", output.getConsoleOutput()); } - @Test public void test410TestResource() throws Exception { - final String TEST_NAME = "test410TestResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -787,8 +716,6 @@ public void test410TestResource() throws Exception { @Test public void test420NotificationAboutJack() throws Exception { - final String TEST_NAME = "test420NotificationAboutJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -814,8 +741,6 @@ public void test420NotificationAboutJack() throws Exception { @Test public void test430NotificationAboutJackType2() throws Exception { - final String TEST_NAME = "test430NotificationAboutJackType2"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -846,8 +771,6 @@ public void test430NotificationAboutJackType2() throws Exception { @Test public void test500ScriptingUsers() throws Exception { - final String TEST_NAME = "test500ScriptingUsers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -877,8 +800,6 @@ public void test500ScriptingUsers() throws Exception { @Test public void test505ScriptingUsersInBackground() throws Exception { - final String TEST_NAME = "test505ScriptingUsersInBackground"; - // GIVEN Task task = getTestTask(); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); @@ -921,8 +842,6 @@ public void test505ScriptingUsersInBackground() throws Exception { @Test public void test507ScriptingUsersInBackgroundAssign() throws Exception { - final String TEST_NAME = "test507ScriptingUsersInBackgroundAssign"; - // GIVEN Task task = getTestTask(); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); @@ -959,8 +878,6 @@ public void test507ScriptingUsersInBackgroundAssign() throws Exception { @Test public void test510GeneratePasswords() throws Exception { - final String TEST_NAME = "test510GeneratePasswords"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -975,7 +892,6 @@ public void test510GeneratePasswords() throws Exception { .asItemDeltas(); modifySystemObjectInRepo(SecurityPolicyType.class, SECURITY_POLICY_OID, itemDeltas, result); - // WHEN ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result); @@ -1000,10 +916,8 @@ public void test510GeneratePasswords() throws Exception { @Test public void test520GeneratePasswordsFullInput() throws Exception { - final String TEST_NAME = "test520GeneratePasswordsFullInput"; - // GIVEN - Task task = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ExecuteScriptType executeScript = parseRealValue(GENERATE_PASSWORDS_2_FILE); @@ -1025,10 +939,8 @@ public void test520GeneratePasswordsFullInput() throws Exception { @Test public void test530GeneratePasswordsReally() throws Exception { - final String TEST_NAME = "test530GeneratePasswordsReally"; - // GIVEN - Task task = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ExecuteScriptType executeScript = parseRealValue(GENERATE_PASSWORDS_3_FILE); @@ -1066,8 +978,6 @@ private void checkPassword(PipelineItem item, String userOid) @Test public void test540SearchUserResolveNamesForRoleMembershipRef() throws Exception { - final String TEST_NAME = "test540SearchUserResolveNamesForRoleMembershipRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1091,8 +1001,6 @@ public void test540SearchUserResolveNamesForRoleMembershipRef() throws Exception @Test public void test545SearchUserResolveRoleMembershipRef() throws Exception { - final String TEST_NAME = "test545SearchUserResolveRoleMembershipRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1116,10 +1024,8 @@ public void test545SearchUserResolveRoleMembershipRef() throws Exception { @Test public void test550UseVariables() throws Exception { - final String TEST_NAME = "test550UseVariables"; - // GIVEN - Task task = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ExecuteScriptType executeScript = parseRealValue(USE_VARIABLES_FILE); @@ -1146,8 +1052,6 @@ public void test550UseVariables() throws Exception { @Test public void test560StartTaskFromTemplate() throws Exception { - final String TEST_NAME = "test560StartTaskFromTemplate"; - // GIVEN Task task = getTestTask(); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); @@ -1194,8 +1098,6 @@ public void test560StartTaskFromTemplate() throws Exception { @Test public void test570IterativeScriptingTask() throws Exception { - final String TEST_NAME = "test570IterativeScriptingTask"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1215,8 +1117,6 @@ public void test570IterativeScriptingTask() throws Exception { @Test(enabled = false) // probably obsolete public void test575ResumeTask() throws Exception { - final String TEST_NAME = "test570ResumeTask"; - // GIVEN Task task = getTestTask(); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); @@ -1248,10 +1148,8 @@ public void test575ResumeTask() throws Exception { // MID-5359 @Test public void test600ModifyJackPasswordInBackground() throws Exception { - final String TEST_NAME = "test600ModifyJackPasswordInBackground"; - // GIVEN - OperationResult result = new OperationResult(DOT_CLASS + TEST_NAME); + OperationResult result = getTestOperationResult(); PrismProperty expression = parseAnyData(MODIFY_JACK_PASSWORD_FILE); prepareNotifications(); @@ -1282,10 +1180,8 @@ public void test600ModifyJackPasswordInBackground() throws Exception { // MID-5359 @Test public void test610ModifyJackPasswordImportingTask() throws Exception { - final String TEST_NAME = "test610ModifyJackPasswordImportingTask"; - // GIVEN - Task opTask = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task opTask = getTestTask(); opTask.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = opTask.getResult(); @@ -1320,10 +1216,8 @@ public void test610ModifyJackPasswordImportingTask() throws Exception { // not using scripting as such, but related... MID-5359 @Test public void test620ModifyJackPasswordViaExecuteChangesAsynchronously() throws Exception { - final String TEST_NAME = "test620ModifyJackPasswordViaExecuteChangesAsynchronously"; - // GIVEN - Task opTask = taskManager.createTaskInstance(DOT_CLASS + TEST_NAME); + Task opTask = getTestTask(); opTask.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = opTask.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java index 8415dd4df18..8f38fc3e0b9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java @@ -79,7 +79,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test200AutzJackNoRole() throws Exception { - final String TEST_NAME = "test200AutzJackNoRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); @@ -93,7 +92,6 @@ public void test200AutzJackNoRole() throws Exception { @Test public void test201AutzJackSuperuserRole() throws Exception { - final String TEST_NAME = "test201AutzJackSuperuserRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SUPERUSER_OID); @@ -108,7 +106,6 @@ public void test201AutzJackSuperuserRole() throws Exception { @Test public void test202AutzJackReadonlyRole() throws Exception { - final String TEST_NAME = "test202AutzJackReadonlyRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_OID); @@ -134,7 +131,6 @@ public void test202AutzJackReadonlyRole() throws Exception { */ @Test public void test202rAutzJackReadonlyReqRole() throws Exception { - final String TEST_NAME = "test202rAutzJackReadonlyReqRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_REQ_OID); @@ -156,7 +152,6 @@ public void test202rAutzJackReadonlyReqRole() throws Exception { */ @Test public void test202eAutzJackReadonlyExecRole() throws Exception { - final String TEST_NAME = "test202eAutzJackReadonlyExecRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_EXEC_OID); @@ -175,7 +170,6 @@ public void test202eAutzJackReadonlyExecRole() throws Exception { @Test public void test202reAutzJackReadonlyReqExecRole() throws Exception { - final String TEST_NAME = "test202reAutzJackReadonlyReqExecRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_OID); @@ -195,7 +189,6 @@ public void test202reAutzJackReadonlyReqExecRole() throws Exception { @Test public void test203AutzJackReadonlyDeepRole() throws Exception { - final String TEST_NAME = "test203AutzJackReadonlyDeepRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_DEEP_OID); @@ -215,7 +208,6 @@ public void test203AutzJackReadonlyDeepRole() throws Exception { @Test public void test203eAutzJackReadonlyDeepExecRole() throws Exception { - final String TEST_NAME = "test203eAutzJackReadonlyDeepExecRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_DEEP_OID); @@ -233,7 +225,6 @@ public void test203eAutzJackReadonlyDeepExecRole() throws Exception { @Test public void test204AutzJackSelfRole() throws Exception { - final String TEST_NAME = "test204AutzJackSelfRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); @@ -287,7 +278,6 @@ public void test204AutzJackSelfRole() throws Exception { @Test public void test204aAutzJackCaseObjectSelfRole() throws Exception { - final String TEST_NAME = "test204aAutzJackCaseObjectSelfRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); @@ -340,7 +330,6 @@ public void test204aAutzJackCaseObjectSelfRole() throws Exception { @Test public void test204bAutzJackCaseAssigneeSelfRole() throws Exception { - final String TEST_NAME = "test204bAutzJackCaseAssigneeSelfRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); @@ -393,7 +382,6 @@ public void test204bAutzJackCaseAssigneeSelfRole() throws Exception { @Test public void test204cAutzJackCaseAssigneeSelfWithDelegatesRole() throws Exception { - final String TEST_NAME = "test204cAutzJackCaseAssigneeSelfWithDelegatesRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_DELEGABLE_OID); @@ -457,7 +445,6 @@ public void test204cAutzJackCaseAssigneeSelfWithDelegatesRole() throws Exception @Test public void test204dAutzJackCaseAssigneeSelfWithNonWorkItemsDelegatesRole() throws Exception { - final String TEST_NAME = "test204dAutzJackCaseAssigneeSelfWithNonWorkItemsDelegatesRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_DELEGABLE_OID); @@ -521,7 +508,6 @@ public void test204dAutzJackCaseAssigneeSelfWithNonWorkItemsDelegatesRole() thro @Test public void test205AutzJackObjectFilterModifyCaribbeanfRole() throws Exception { - final String TEST_NAME = "test205AutzJackObjectFilterModifyCaribbeanfRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_OBJECT_FILTER_MODIFY_CARIBBEAN_OID); @@ -546,7 +532,6 @@ public void test205AutzJackObjectFilterModifyCaribbeanfRole() throws Exception { @Test public void test207AutzJackObjectFilterCaribbeanRole() throws Exception { - final String TEST_NAME = "test207AutzJackObjectFilterCaribbeanfRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_OBJECT_FILTER_CARIBBEAN_OID); @@ -584,7 +569,6 @@ public void test207AutzJackObjectFilterCaribbeanRole() throws Exception { @Test public void test207rAutzJackObjectFilterCaribbeanRole() throws Exception { - final String TEST_NAME = "test207rAutzJackObjectFilterCaribbeanRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_OBJECT_FILTER_CARIBBEAN_RAW_OID); @@ -626,7 +610,7 @@ public void test207rAutzJackObjectFilterCaribbeanRole() throws Exception { */ @Test public void test208AutzJackReadSomeRoles() throws Exception { - testAutzJackReadSomeRoles("test208AutzJackReadSomeRoles", ROLE_READ_SOME_ROLES_OID); + testAutzJackReadSomeRoles(ROLE_READ_SOME_ROLES_OID); } /** @@ -634,10 +618,10 @@ public void test208AutzJackReadSomeRoles() throws Exception { */ @Test public void test208sAutzJackReadSomeRoles() throws Exception { - testAutzJackReadSomeRoles("test208sAutzJackReadSomeRoles", ROLE_READ_SOME_ROLES_SUBTYPE_OID); + testAutzJackReadSomeRoles(ROLE_READ_SOME_ROLES_SUBTYPE_OID); } - public void testAutzJackReadSomeRoles(final String TEST_NAME, String roleOid) throws Exception { + public void testAutzJackReadSomeRoles(String roleOid) throws Exception { // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, roleOid); @@ -676,7 +660,6 @@ public void testAutzJackReadSomeRoles(final String TEST_NAME, String roleOid) th */ @Test public void test209AutzJackSuperuserAndGuiAccessRole() throws Exception { - final String TEST_NAME = "test209AutzJackSuperuserAndGuiAccessRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SUPERUSER_OID); @@ -694,7 +677,6 @@ public void test209AutzJackSuperuserAndGuiAccessRole() throws Exception { */ @Test public void test210AutzJackPropReadAllModifySome() throws Exception { - final String TEST_NAME = "test210AutzJackPropReadAllModifySome"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_OID); @@ -731,7 +713,6 @@ public void test210AutzJackPropReadAllModifySome() throws Exception { */ @Test public void test211AutzJackPropReadAllModifySomeUser() throws Exception { - final String TEST_NAME = "test211AutzJackPropReadAllModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_USER_OID); @@ -779,7 +760,6 @@ public void test211AutzJackPropReadAllModifySomeUser() throws Exception { */ @Test public void test212AutzJackPropReadAllModifySomeUserPartial() throws Exception { - final String TEST_NAME = "test212AutzJackPropReadAllModifySomeUserPartial"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_USER_PARTIAL_OID); @@ -842,14 +822,12 @@ private void assertJackEditSchemaReadAllModifySome(PrismObject userJac @Test public void test215AutzJackPropReadSomeModifySome() throws Exception { - final String TEST_NAME = "test215AutzJackPropReadSomeModifySome"; - testAutzJackPropReadSomeModifySome(TEST_NAME, ROLE_PROP_READ_SOME_MODIFY_SOME_OID); + testAutzJackPropReadSomeModifySome(ROLE_PROP_READ_SOME_MODIFY_SOME_OID); } @Test public void test215reAutzJackPropReadSomeModifySomeReqExec() throws Exception { - final String TEST_NAME = "test215reAutzJackPropReadSomeModifySomeReqExec"; - testAutzJackPropReadSomeModifySome(TEST_NAME, ROLE_PROP_READ_SOME_MODIFY_SOME_REQ_EXEC_OID); + testAutzJackPropReadSomeModifySome(ROLE_PROP_READ_SOME_MODIFY_SOME_REQ_EXEC_OID); } /** @@ -857,13 +835,12 @@ public void test215reAutzJackPropReadSomeModifySomeReqExec() throws Exception { */ @Test public void test216AutzJackPropReadSomeModifySomeUser() throws Exception { - final String TEST_NAME = "test216AutzJackPropReadSomeModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID); login(USER_JACK_USERNAME); - doReadSomeModifySomeUser(TEST_NAME); + doReadSomeModifySomeUser(); } /** @@ -871,17 +848,15 @@ public void test216AutzJackPropReadSomeModifySomeUser() throws Exception { */ @Test public void test217AutzJackPropGetSearchSomeModifySomeUser() throws Exception { - final String TEST_NAME = "test217AutzJackPropGetSearchSomeModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_GET_SEARCH_SOME_MODIFY_SOME_USER_OID); login(USER_JACK_USERNAME); - doReadSomeModifySomeUser(TEST_NAME); + doReadSomeModifySomeUser(); } - private void doReadSomeModifySomeUser(final String TEST_NAME) throws Exception { - + private void doReadSomeModifySomeUser() throws Exception { // WHEN when(); @@ -913,7 +888,7 @@ private void doReadSomeModifySomeUser(final String TEST_NAME) throws Exception { assertGlobalStateUntouched(); } - public void testAutzJackPropReadSomeModifySome(final String TEST_NAME, String roleOid) throws Exception { + public void testAutzJackPropReadSomeModifySome(String roleOid) throws Exception { // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, roleOid); @@ -929,7 +904,6 @@ public void testAutzJackPropReadSomeModifySome(final String TEST_NAME, String ro @Test public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { - final String TEST_NAME = "test218AutzJackPropReadSomeModifySomeExecAll"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_EXEC_ALL_OID); @@ -1008,7 +982,6 @@ public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { */ @Test public void test219AutzJackPropReadSomeModifySomeFullName() throws Exception { - final String TEST_NAME = "test219AutzJackPropReadSomeModifySomeFullName"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_FULLNAME_OID); @@ -1168,7 +1141,6 @@ public void test219AutzJackPropReadSomeModifySomeFullName() throws Exception { @Test public void test220AutzJackPropDenyModifySome() throws Exception { - final String TEST_NAME = "test220AutzJackPropDenyModifySome"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_DENY_MODIFY_SOME_OID); @@ -1233,7 +1205,6 @@ public void test220AutzJackPropDenyModifySome() throws Exception { @Test public void test230AutzJackMasterMinistryOfRum() throws Exception { - final String TEST_NAME = "test230AutzJackMasterMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MASTER_MINISTRY_OF_RUM_OID); @@ -1264,7 +1235,6 @@ public void test230AutzJackMasterMinistryOfRum() throws Exception { @Test public void test232AutzJackReadOrgMinistryOfRum() throws Exception { - final String TEST_NAME = "test232AutzJackReadOrgMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ORG_READ_ORGS_MINISTRY_OF_RUM_OID); @@ -1295,7 +1265,6 @@ public void test232AutzJackReadOrgMinistryOfRum() throws Exception { */ @Test public void test240AutzJackManagerFullControlNoOrg() throws Exception { - final String TEST_NAME = "test240AutzJackManagerFullControlNoOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1345,7 +1314,6 @@ public void test240AutzJackManagerFullControlNoOrg() throws Exception { */ @Test public void test241AutzJackManagerFullControlMemberMinistryOfRum() throws Exception { - final String TEST_NAME = "test241AutzJackManagerFullControlMemberMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1361,7 +1329,7 @@ public void test241AutzJackManagerFullControlMemberMinistryOfRum() throws Except // WHEN when(); - assertJack24xMember(accountOid, true); + assertJack24xMember(accountOid); assertGlobalStateUntouched(); } @@ -1430,7 +1398,6 @@ public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() th */ @Test public void test245AutzJackManagerUserAdminMemberMinistryOfRum() throws Exception { - final String TEST_NAME = "test245AutzJackManagerUserAdminMemberMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1446,7 +1413,7 @@ public void test245AutzJackManagerUserAdminMemberMinistryOfRum() throws Exceptio // WHEN when(); - assertJack24xMember(accountOid, false); + assertJack24xMember(accountOid); assertGlobalStateUntouched(); } @@ -1508,7 +1475,7 @@ public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() thro assertGlobalStateUntouched(); } - private void assertJack24xMember(String accountOid, boolean fullControl) throws Exception { + private void assertJack24xMember(String accountOid) throws Exception { assertReadDeny(0); assertAddDeny(); assertModifyDeny(); @@ -1728,7 +1695,6 @@ private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) @Test public void test250AutzJackSelfAccountsRead() throws Exception { - final String TEST_NAME = "test250AutzJackSelfAccountsRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1804,7 +1770,6 @@ public void test250AutzJackSelfAccountsRead() throws Exception { @Test public void test255AutzJackSelfAccountsReadWrite() throws Exception { - final String TEST_NAME = "test255AutzJackSelfAccountsReadWrite"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_READ_WRITE_OID); @@ -1869,7 +1834,6 @@ public void test255AutzJackSelfAccountsReadWrite() throws Exception { @Test public void test256AutzJackSelfAccountsPartialControl() throws Exception { - final String TEST_NAME = "test256AutzJackSelfAccountsPartialControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_PARTIAL_CONTROL_OID); @@ -1923,35 +1887,11 @@ public void test256AutzJackSelfAccountsPartialControl() throws Exception { PrismObjectDefinition rDef = modelInteractionService.getEditObjectDefinition(user, AuthorizationPhaseType.REQUEST, task, result); assertItemFlags(rDef, PASSWORD_PATH, true, false, false); -// // Linked to jack -// assertAllow("add jack's account to jack", new Attempt() { -// @Override -// public void run(Task task, OperationResult result) throws Exception { -// modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result); -// } -// }); -// user = getUser(USER_JACK_OID); -// display("Jack after red account link", user); -// String accountRedOid = getLinkRefOid(user, RESOURCE_DUMMY_RED_OID); -// assertNotNull("Strange, red account not linked to jack", accountRedOid); -// -// // Linked to other user -// assertDeny("add gyubrush's account", new Attempt() { -// @Override -// public void run(Task task, OperationResult result) throws Exception { -// modifyUserAddAccount(USER_LARGO_OID, ACCOUNT_HERMAN_DUMMY_FILE, task, result); -// } -// }); -// -// assertDeleteAllow(ShadowType.class, accountRedOid); -// assertDeleteDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - assertGlobalStateUntouched(); } @Test public void test258AutzJackSelfAccountsPartialControlPassword() throws Exception { - final String TEST_NAME = "test258AutzJackSelfAccountsPartialControlPassword"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_PARTIAL_CONTROL_PASSWORD_OID); @@ -2009,12 +1949,11 @@ public void test258AutzJackSelfAccountsPartialControlPassword() throws Exception } /** - * test getEditObjectDefinition for shadow. It should also call and apply edited schema for attributes - * @throws Exception + * Test getEditObjectDefinition for shadow. + * It should also call and apply edited schema for attributes. */ @Test public void test259AutzJackSelfAccountsPartialControl() throws Exception { - final String TEST_NAME = "test259AutzJackSelfAccountsPartialControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_PARTIAL_CONTROL_PASSWORD_OID); @@ -2084,7 +2023,6 @@ public void test259AutzJackSelfAccountsPartialControl() throws Exception { @Test public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { - final String TEST_NAME = "test260AutzJackObjectFilterLocationShadowRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_FILTER_OBJECT_USER_LOCATION_SHADOWS_OID); @@ -2120,9 +2058,7 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { // Linked to jack assertAllow("add jack's account to jack", - (task, result) -> { - modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result); - }); + (task, result) -> modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result)); PrismObject user = getUser(USER_JACK_OID); display("Jack after red account link", user); String accountRedOid = getLinkRefOid(user, RESOURCE_DUMMY_RED_OID); @@ -2131,7 +2067,7 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { assertGlobalStateUntouched(); - displayCleanup(TEST_NAME); + displayCleanup(); login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -2150,12 +2086,10 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { /** - * creates user and assigns role at the same time - * @throws Exception + * Creates user and assigns role at the same time. */ @Test public void test261AutzAngelicaObjectFilterLocationCreateUserShadowRole() throws Exception { - final String TEST_NAME = "test261AutzJackObjectFilterLocationCreateUserShadowRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -2186,7 +2120,6 @@ public void test261AutzAngelicaObjectFilterLocationCreateUserShadowRole() throws @Test public void test270AutzJackAssignApplicationRoles() throws Exception { - final String TEST_NAME = "test270AutzJackAssignApplicationRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_APPLICATION_ROLES_OID); @@ -2240,7 +2173,6 @@ public void test270AutzJackAssignApplicationRoles() throws Exception { @Test public void test272AutzJackAssignAnyRoles() throws Exception { - final String TEST_NAME = "test272AutzJackAssignAnyRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ANY_ROLES_OID); @@ -2299,7 +2231,6 @@ public void test272AutzJackAssignAnyRoles() throws Exception { */ @Test public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { - final String TEST_NAME = "test273AutzJackRedyAssignmentExceptionRules"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ANY_ROLES_OID); @@ -2352,7 +2283,6 @@ public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { @Test public void test274AutzJackAssignNonApplicationRoles() throws Exception { - final String TEST_NAME = "test274AutzJackAssignNonApplicationRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_NON_APPLICATION_ROLES_OID); @@ -2399,7 +2329,6 @@ public void test274AutzJackAssignNonApplicationRoles() throws Exception { @Test public void test275aAutzJackAssignRequestableRoles() throws Exception { - final String TEST_NAME = "test275aAutzJackAssignRequestableRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2453,7 +2382,6 @@ public void test275aAutzJackAssignRequestableRoles() throws Exception { */ @Test public void test275bAutzJackAssignRequestableOrgs() throws Exception { - final String TEST_NAME = "test275bAutzJackAssignRequestableOrgs"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_END_USER_REQUESTABLE_ABSTRACTROLES_OID); @@ -2497,7 +2425,6 @@ public void test275bAutzJackAssignRequestableOrgs() throws Exception { */ @Test public void test275cAutzJackAssignRequestableRolesAndInduceAnyRole() throws Exception { - final String TEST_NAME = "test275cAutzJackAssignRequestableRolesAndInduceAnything"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2553,7 +2480,6 @@ public void test275cAutzJackAssignRequestableRolesAndInduceAnyRole() throws Exce */ @Test public void test276AutzJackAssignRequestableRolesWithOrgRef() throws Exception { - final String TEST_NAME = "test276AutzJackAssignRequestableRolesWithOrgRef"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2606,7 +2532,6 @@ public void test276AutzJackAssignRequestableRolesWithOrgRef() throws Exception { */ @Test public void test277AutzJackAssignRequestableRolesWithOrgRefSecondTime() throws Exception { - final String TEST_NAME = "test277AutzJackAssignRequestableRolesWithOrgRefSecondTime"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2688,7 +2613,6 @@ public void test277AutzJackAssignRequestableRolesWithOrgRefSecondTime() throws E */ @Test public void test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta() throws Exception { - final String TEST_NAME = "test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2756,7 +2680,6 @@ public void test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta() throws */ @Test public void test279AutzJackAssignRequestableRolesWithTenantRef() throws Exception { - final String TEST_NAME = "test279AutzJackAssignRequestableRolesWithTenantRef"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); @@ -2809,7 +2732,6 @@ public void test279AutzJackAssignRequestableRolesWithTenantRef() throws Exceptio */ @Test public void test280AutzJackEndUser() throws Exception { - final String TEST_NAME = "test280AutzJackEndUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -2896,7 +2818,6 @@ public void test280AutzJackEndUser() throws Exception { @Test public void test281AutzJackEndUserSecondTime() throws Exception { - final String TEST_NAME = "test281AutzJackEndUserSecondTime"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -2912,7 +2833,7 @@ public void test281AutzJackEndUserSecondTime() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 1); - user = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); // MID-3136 assertAllow("assign business role to jack (no param)", @@ -2953,7 +2874,7 @@ private void assertCredentialsPolicy(PrismObject user) throws ObjectNo TestUtil.assertSuccess(result); assertNotNull("No credentials policy for "+user, credentialsPolicy); SecurityQuestionsCredentialsPolicyType securityQuestions = credentialsPolicy.getSecurityQuestions(); - assertEquals("Unexepected number of security questions for "+user, 2, securityQuestions.getQuestion().size()); + assertEquals("Unexpected number of security questions for "+user, 2, securityQuestions.getQuestion().size()); } /** @@ -2961,7 +2882,6 @@ private void assertCredentialsPolicy(PrismObject user) throws ObjectNo */ @Test public void test282AutzJackEndUserAndModify() throws Exception { - final String TEST_NAME = "test282AutzJackEndUserAndModify"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3001,7 +2921,6 @@ public void test282AutzJackEndUserAndModify() throws Exception { @Test public void test283AutzJackModifyAndEndUser() throws Exception { - final String TEST_NAME = "test283AutzJackModifyAndEndUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3035,7 +2954,6 @@ public void test283AutzJackModifyAndEndUser() throws Exception { @Test public void test285AutzJackEndUserAndAdd() throws Exception { - final String TEST_NAME = "test285AutzJackEndUserAndAdd"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3068,7 +2986,6 @@ public void test285AutzJackEndUserAndAdd() throws Exception { @Test public void test295AutzJackAssignOrgRelation() throws Exception { - final String TEST_NAME = "test295AutzJackAssignOrgRelation"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3108,7 +3025,6 @@ public void test295AutzJackAssignOrgRelation() throws Exception { @Test public void test300AutzAnonymous() throws Exception { - final String TEST_NAME = "test300AutzAnonymous"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); @@ -3122,7 +3038,6 @@ public void test300AutzAnonymous() throws Exception { @Test public void test310AutzJackNoRolePrivileged() throws Exception { - final String TEST_NAME = "test310AutzJackNoRolePrivileged"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); @@ -3152,7 +3067,6 @@ public void test310AutzJackNoRolePrivileged() throws Exception { @Test public void test312AutzAnonymousPrivileged() throws Exception { - final String TEST_NAME = "test312AutzAnonymousPrivileged"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); @@ -3182,7 +3096,6 @@ public void test312AutzAnonymousPrivileged() throws Exception { @Test public void test313AutzAnonymousPrivilegedRestore() throws Exception { - final String TEST_NAME = "test313AutzAnonymousPrivilegedRestore"; // GIVEN cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); @@ -3204,7 +3117,6 @@ public void test313AutzAnonymousPrivilegedRestore() throws Exception { @Test public void test360AutzJackAuditorRole() throws Exception { - final String TEST_NAME = "test360AutzJackAuditorRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_AUDITOR_OID); @@ -3229,7 +3141,6 @@ public void test360AutzJackAuditorRole() throws Exception { */ @Test public void test370AutzJackLimitedUserAdmin() throws Exception { - final String TEST_NAME = "test370AutzJackLimitedUserAdmin"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_USER_ADMIN_OID); @@ -3256,7 +3167,6 @@ public void test370AutzJackLimitedUserAdmin() throws Exception { @Test public void test380AutzJackSelfTaskOwner() throws Exception { - final String TEST_NAME = "test380AutzJackSelfTaskOwner"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_TASK_OWNER_OID); @@ -3293,16 +3203,12 @@ public void test380AutzJackSelfTaskOwner() throws Exception { private void assertTaskAddAllow(String oid, String name, String ownerOid, String handlerUri) throws Exception { assertAllow("add task "+name, - (task, result) -> { - addTask(oid, name, ownerOid, handlerUri, task, result); - }); + (task, result) -> addTask(oid, name, ownerOid, handlerUri, task, result)); } private void assertTaskAddDeny(String oid, String name, String ownerOid, String handlerUri) throws Exception { assertDeny("add task "+name, - (task, result) -> { - addTask(oid, name, ownerOid, handlerUri, task, result); - }); + (task, result) -> addTask(oid, name, ownerOid, handlerUri, task, result)); } private void addTask(String oid, String name, String ownerOid, String handlerUri, Task execTask, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java index 9bcbaa572e3..4e49375c6c3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java @@ -147,8 +147,6 @@ private String getUserName(int i, boolean precise) { */ @Test public void test100SuspendWhileIcfSync() throws Exception { - final String TEST_NAME = "test100SuspendWhileIcfSync"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -178,8 +176,6 @@ public void test100SuspendWhileIcfSync() throws Exception { */ @Test public void test105SuspendWhileIcfSyncImprecise() throws Exception { - final String TEST_NAME = "test105SuspendWhileIcfSyncImprecise"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -213,8 +209,6 @@ public void test105SuspendWhileIcfSyncImprecise() throws Exception { */ @Test public void test110SuspendWhileProcessing() throws Exception { - final String TEST_NAME = "test110SuspendWhileProcessing"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -269,8 +263,6 @@ public void test110SuspendWhileProcessing() throws Exception { */ @Test public void test115SuspendWhileProcessingImprecise() throws Exception { - final String TEST_NAME = "test115SuspendWhileProcessingImprecise"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -313,8 +305,6 @@ public void test115SuspendWhileProcessingImprecise() throws Exception { */ @Test public void test120Batched() throws Exception { - final String TEST_NAME = "test120Batched"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -381,8 +371,6 @@ public void test120Batched() throws Exception { */ @Test public void test125BatchedImprecise() throws Exception { - final String TEST_NAME = "test125BatchedImprecise"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -428,8 +416,6 @@ public void test125BatchedImprecise() throws Exception { */ @Test public void test130Error() throws Exception { - final String TEST_NAME = "test130Error"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -489,8 +475,6 @@ public void test130Error() throws Exception { */ @Test public void test135ErrorImprecise() throws Exception { - final String TEST_NAME = "test135ErrorImprecise"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -556,8 +540,6 @@ public void test135ErrorImprecise() throws Exception { */ @Test public void test140DryRun() throws Exception { - final String TEST_NAME = "test140DryRun"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); @@ -595,8 +577,6 @@ public void test140DryRun() throws Exception { */ @Test public void test150DryRunWithUpdate() throws Exception { - final String TEST_NAME = "test150DryRunWithUpdate"; - // GIVEN AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java index 60912877226..b6ae6ac864c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java @@ -39,7 +39,7 @@ protected void waitForValidityNextRunAssertSuccess() throws Exception { protected void assertLastScanTimestamp(String taskOid, XMLGregorianCalendar startCal, XMLGregorianCalendar endCal) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - OperationResult result = new OperationResult(TestValidityRecomputeTaskPartitioned.class.getName() + ".assertLastScanTimestamp"); + OperationResult result = createOperationResult("assertLastScanTimestamp"); Task master = taskManager.getTask(taskOid, result); for (Task subtask : master.listSubtasks(result)) { super.assertLastScanTimestamp(subtask.getOid(), startCal, endCal); diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index 38355aba8f2..08711b48218 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -25,9 +25,6 @@ import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; -import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; - import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.mutable.MutableInt; import org.jetbrains.annotations.NotNull; @@ -103,7 +100,9 @@ import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; +import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; import com.evolveum.midpoint.schema.statistics.StatisticsUtil; +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; import com.evolveum.midpoint.schema.util.*; import com.evolveum.midpoint.security.api.Authorization; import com.evolveum.midpoint.security.api.AuthorizationConstants; @@ -402,7 +401,9 @@ protected void applyResourceSchema(ShadowType accountType, ResourceType resource IntegrationTestTools.applyResourceSchema(accountType, resourceType, prismContext); } - protected void assertUsers(int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertUsers(int expectedNumberOfUsers) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(UserType.class, expectedNumberOfUsers); } @@ -1622,7 +1623,11 @@ protected void assignPolicyRule(Class type, String focu assign(type, focusOid, assignmentType, task, result); } - protected void assign(Class type, String focusOid, AssignmentType assignmentType, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + protected void assign(Class type, String focusOid, + AssignmentType assignmentType, Task task, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException { Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(assignmentType, true)); ObjectDelta userDelta = prismContext.deltaFactory().object().createModifyDelta(focusOid, modifications, type @@ -1630,7 +1635,9 @@ protected void assign(Class type, String focusOid, Assi executeChanges(userDelta, null, task, result); } - protected PrismObject getUser(String userOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject getUser(String userOid) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = createPlainTask("getUser"); OperationResult result = task.getResult(); PrismObject user = modelService.getObject(UserType.class, userOid, null, task, result); @@ -1768,7 +1775,8 @@ protected void assertNoObject( } } - protected void assertObjectByName(Class type, String name, Task task, OperationResult result) + protected void assertObjectByName( + Class type, String name, Task task, OperationResult result) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException { SearchResultList> objects = modelService @@ -1779,7 +1787,8 @@ protected void assertObjectByName(Class type, String n } } - protected void assertNoObjectByName(Class type, String name, Task task, OperationResult result) + protected void assertNoObjectByName( + Class type, String name, Task task, OperationResult result) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException { SearchResultList> objects = modelService @@ -2018,7 +2027,8 @@ protected static void assertAssignedRoles(PrismObject u MidPointAsserts.assertAssignedRoles(user, roleOids); } - protected AssignmentType assertInducedRole(PrismObject role, String roleOid) { + protected AssignmentType assertInducedRole( + PrismObject role, String roleOid) { return MidPointAsserts.assertInducedRole(role, roleOid); } @@ -2135,7 +2145,8 @@ protected void assertDelegatedRef(PrismObject focus, St PrismAsserts.assertSets("Wrong values in delegatedRef in " + focus, refOids, oids); } - protected void assertNotAssignedRole(PrismObject focus, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertNotAssignedRole( + PrismObject focus, String roleOid, Task task, OperationResult result) { MidPointAsserts.assertNotAssignedRole(focus, roleOid); } @@ -2188,7 +2199,7 @@ protected void assertHasOrg(String userOid, String orgOid, Task task, OperationR assertAssignedOrg(user, orgOid); } - protected void assertHasOrgs(PrismObject user, String... orgOids) throws Exception { + protected void assertHasOrgs(PrismObject user, String... orgOids) { for (String orgOid : orgOids) { assertHasOrg(user, orgOid); } @@ -2394,7 +2405,8 @@ protected void assertInducedRoles(PrismObject ro } } - protected void assertAssignments(PrismObject user, Class expectedType, int expectedNumber) { + protected void assertAssignments( + PrismObject user, Class expectedType, int expectedNumber) { MidPointAsserts.assertAssignments(user, expectedType, expectedNumber); } @@ -2411,11 +2423,13 @@ protected void assertAssignedNoOrg(PrismObject user) { assertAssignedNo(user, OrgType.COMPLEX_TYPE); } - protected void assertAssignedNoRole(PrismObject focus, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedNoRole( + PrismObject focus, Task task, OperationResult result) { assertAssignedNoRole(focus); } - protected void assertAssignedNoRole(String userOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedNoRole(String userOid, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedNoRole(user); } @@ -2436,12 +2450,14 @@ protected void assertAssignedNo(PrismObject user, QName } } - protected void assertAssignedAccount(String userOid, String resourceOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedAccount( + String userOid, String resourceOid, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedAccount(user, resourceOid); } - protected AssignmentType assertAssignedAccount(PrismObject user, String resourceOid) throws ObjectNotFoundException, SchemaException { + protected AssignmentType assertAssignedAccount(PrismObject user, String resourceOid) { UserType userType = user.asObjectable(); for (AssignmentType assignmentType : userType.getAssignment()) { ConstructionType construction = assignmentType.getConstruction(); @@ -2458,7 +2474,7 @@ protected AssignmentType assertAssignedAccount(PrismObject user, Strin return null; // not reached } - protected void assertAssignedNoAccount(PrismObject user, String resourceOid) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedNoAccount(PrismObject user, String resourceOid) { UserType userType = user.asObjectable(); for (AssignmentType assignmentType : userType.getAssignment()) { ConstructionType construction = assignmentType.getConstruction(); @@ -2712,7 +2728,8 @@ protected void setConflictResolution(QName objectType, String subType, ConflictR } - protected void setConflictResolutionAction(QName objectType, String subType, ConflictResolutionActionType conflictResolutionAction, OperationResult parentResult) + protected void setConflictResolutionAction(QName objectType, String subType, + ConflictResolutionActionType conflictResolutionAction, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { ConflictResolutionType conflictResolutionType = new ConflictResolutionType(); conflictResolutionType.action(conflictResolutionAction); @@ -5604,7 +5621,7 @@ protected Consumer createShowTaskTreeConsumer(long period) { return task -> { try { if (lastTimeShown.get() + period < System.currentTimeMillis()) { - dumpTaskTree(task.getOid(), createOperationalResult()); + dumpTaskTree(task.getOid(), createOperationResult()); lastTimeShown.set(System.currentTimeMillis()); } } catch (CommonException e) { diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/AssignmentCandidatesSpecificationAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/AssignmentCandidatesSpecificationAsserter.java index e9583a0b357..cb78cd465ba 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/AssignmentCandidatesSpecificationAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/AssignmentCandidatesSpecificationAsserter.java @@ -11,7 +11,7 @@ import org.testng.AssertJUnit; import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; /** @@ -49,7 +49,7 @@ public AssignmentCandidatesSpecificationAsserter display() { } public AssignmentCandidatesSpecificationAsserter display(String message) { - IntegrationTestTools.display(message, candidateSpec); + PrismTestUtil.display(message, candidateSpec); return this; } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/CompiledGuiProfileAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/CompiledGuiProfileAsserter.java index 608b2d5b242..818b826e5be 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/CompiledGuiProfileAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/CompiledGuiProfileAsserter.java @@ -13,7 +13,7 @@ import org.testng.AssertJUnit; import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; /** @@ -89,7 +89,7 @@ public CompiledGuiProfileAsserter display() { } public CompiledGuiProfileAsserter display(String message) { - IntegrationTestTools.display(message, compiledGuiProfile); + PrismTestUtil.display(message, compiledGuiProfile); return this; } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ElementContextAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ElementContextAsserter.java index 166a9172c59..784c934432d 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ElementContextAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ElementContextAsserter.java @@ -9,7 +9,7 @@ import static org.testng.AssertJUnit.assertNull; import com.evolveum.midpoint.model.api.context.ModelElementContext; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.test.asserter.prism.ObjectDeltaAsserter; import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter; @@ -98,7 +98,7 @@ public ElementContextAsserter display() { } public ElementContextAsserter display(String message) { - IntegrationTestTools.display(message, elementContext); + PrismTestUtil.display(message, elementContext); return this; } } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/FocusContextAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/FocusContextAsserter.java index 0be01dfdbd8..cc885dd8d85 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/FocusContextAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/FocusContextAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.model.test.asserter; import com.evolveum.midpoint.model.api.context.ModelElementContext; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.prism.ObjectDeltaAsserter; import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -86,7 +86,7 @@ public FocusContextAsserter display() { @Override public FocusContextAsserter display(String message) { - IntegrationTestTools.display(message, getFocusContext()); + PrismTestUtil.display(message, getFocusContext()); return this; } } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ModelContextAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ModelContextAsserter.java index b4c8a3076cb..56a00ce1cb4 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ModelContextAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ModelContextAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.model.test.asserter; import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -64,7 +64,7 @@ protected String desc() { } public ModelContextAsserter display(String message) { - IntegrationTestTools.display(message, modelContext); + PrismTestUtil.display(message, modelContext); return this; } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ProjectionContextAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ProjectionContextAsserter.java index 681af50374d..190d6c6fd32 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ProjectionContextAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/ProjectionContextAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.model.test.asserter; import com.evolveum.midpoint.model.api.context.ModelProjectionContext; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.test.asserter.prism.ObjectDeltaAsserter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -94,7 +94,7 @@ public ProjectionContextAsserter display() { @Override public ProjectionContextAsserter display(String message) { - IntegrationTestTools.display(message, getProjectionContext()); + PrismTestUtil.display(message, getProjectionContext()); return this; } } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationAsserter.java index 2789b69c65e..d568d91e601 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationAsserter.java @@ -8,8 +8,8 @@ import com.evolveum.midpoint.model.api.RoleSelectionSpecification; import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.test.asserter.prism.ObjectFilterAsserter; import com.evolveum.midpoint.util.PrettyPrinter; @@ -75,7 +75,7 @@ public RoleSelectionSpecificationAsserter display() { } public RoleSelectionSpecificationAsserter display(String message) { - IntegrationTestTools.display(message, roleSelectionSpec); + PrismTestUtil.display(message, roleSelectionSpec); return this; } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationRelationAsserter.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationRelationAsserter.java index 15c639c9e1f..1dee38c6f9f 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationRelationAsserter.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/asserter/RoleSelectionSpecificationRelationAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.model.test.asserter; import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.test.asserter.prism.ObjectFilterAsserter; @@ -32,7 +32,7 @@ public RoleSelectionSpecificationRelationAsserter display() { } public RoleSelectionSpecificationRelationAsserter display(String message) { - IntegrationTestTools.display(message, filter); + PrismTestUtil.display(message, filter); return this; } diff --git a/model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTransportUtils.java b/model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTransportUtils.java index a88ec58e19d..30cd805e66f 100644 --- a/model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTransportUtils.java +++ b/model/notifications-impl/src/test/java/com/evolveum/midpoint/notifications/impl/TestTransportUtils.java @@ -6,6 +6,18 @@ */ package com.evolveum.midpoint.notifications.impl; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.xml.sax.SAXException; + import com.evolveum.midpoint.notifications.impl.api.transports.TransportUtil; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; @@ -17,26 +29,12 @@ import com.evolveum.midpoint.test.util.AbstractSpringTest; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.NotificationTransportConfigurationType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.testng.AssertJUnit.assertTrue; - /** * @author skublik */ -@ContextConfiguration(locations = {"classpath:ctx-task.xml", +@ContextConfiguration(locations = { "classpath:ctx-task.xml", "classpath:ctx-repo-cache.xml", "classpath:ctx-provisioning.xml", "classpath*:ctx-repository-test.xml", @@ -49,11 +47,9 @@ "classpath:ctx-model.xml", "classpath:ctx-model-common.xml", "classpath:ctx-notifications-test.xml", - "classpath*:ctx-notifications.xml"}) + "classpath*:ctx-notifications.xml" }) public class TestTransportUtils extends AbstractSpringTest { - private static final Trace LOGGER = TraceManager.getTrace(TestTransportUtils.class); - @Autowired protected ExpressionFactory expressionFactory; @Autowired protected TaskManager taskManager; @@ -65,8 +61,6 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void test010CheckVariablesWhiteList() { - final String TEST_NAME = "test010CheckVariablesWhiteList"; - // GIVEN NotificationTransportConfigurationType config = new NotificationTransportConfigurationType(); @@ -88,26 +82,24 @@ public void test010CheckVariablesWhiteList() { recipients.add("janko@evolveum.eu"); // WHEN - TransportUtil.validateRecipient(allowRecipient, forbiddenRecipient, recipients, config, task, task.getResult(), expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER); + TransportUtil.validateRecipient(allowRecipient, forbiddenRecipient, recipients, config, task, task.getResult(), expressionFactory, MiscSchemaUtil.getExpressionProfile(), logger); // THEN then(); - assertTrue("Expected <4> allowed recipient(s), but was <" +allowRecipient.size()+ ">", allowRecipient.size() == 4); + assertTrue("Expected <4> allowed recipient(s), but was <" + allowRecipient.size() + ">", allowRecipient.size() == 4); assertTrue("janko@evodevel.com shoud be allowed, but isn't.", allowRecipient.contains("janko@evodevel.com")); assertTrue("janko@evolveum.com shoud be allowed, but isn't.", allowRecipient.contains("janko@evolveum.com")); assertTrue("viliam@evodevel.com shoud be allowed, but isn't.", allowRecipient.contains("viliam@evodevel.com")); assertTrue("majka@evodevel.eu shoud be allowed, but isn't.", allowRecipient.contains("majka@evodevel.eu")); - assertTrue("Expected <2> forbidden recipient(s), but was <" +forbiddenRecipient.size()+ ">", forbiddenRecipient.size() == 2); + assertTrue("Expected <2> forbidden recipient(s), but was <" + forbiddenRecipient.size() + ">", forbiddenRecipient.size() == 2); assertTrue("jack@evodevel.sk shoud be forbidden, but isn't.", forbiddenRecipient.contains("jack@evodevel.sk")); assertTrue("janko@evolveum.eu shoud be forbidden, but isn't.", forbiddenRecipient.contains("janko@evolveum.eu")); } @Test public void test020CheckVariablesBlackList() { - final String TEST_NAME = "test020CheckVariablesBlackList"; - // GIVEN NotificationTransportConfigurationType config = new NotificationTransportConfigurationType(); @@ -129,18 +121,18 @@ public void test020CheckVariablesBlackList() { recipients.add("janko@evolveum.eu"); // WHEN - TransportUtil.validateRecipient(allowRecipient, forbiddenRecipient, recipients, config, task, task.getResult(), expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER); + TransportUtil.validateRecipient(allowRecipient, forbiddenRecipient, recipients, config, task, task.getResult(), expressionFactory, MiscSchemaUtil.getExpressionProfile(), logger); // THEN then(); - assertTrue("Expected <4> forbidden recipient(s), but was <" +forbiddenRecipient.size()+ ">", forbiddenRecipient.size() == 4); + assertTrue("Expected <4> forbidden recipient(s), but was <" + forbiddenRecipient.size() + ">", forbiddenRecipient.size() == 4); assertTrue("janko@evodevel.com shoud be forbidden, but isn't.", forbiddenRecipient.contains("janko@evodevel.com")); assertTrue("janko@evolveum.com shoud be forbidden, but isn't.", forbiddenRecipient.contains("janko@evolveum.com")); assertTrue("viliam@evodevel.com shoud be forbidden, but isn't.", forbiddenRecipient.contains("viliam@evodevel.com")); assertTrue("majka@evodevel.eu shoud be forbidden, but isn't.", forbiddenRecipient.contains("majka@evodevel.eu")); - assertTrue("Expected <2> allowed recipient(s), but was <" +allowRecipient.size()+ ">", allowRecipient.size() == 2); + assertTrue("Expected <2> allowed recipient(s), but was <" + allowRecipient.size() + ">", allowRecipient.size() == 2); assertTrue("jack@evodevel.sk shoud be allowed, but isn't.", allowRecipient.contains("jack@evodevel.sk")); assertTrue("janko@evolveum.eu shoud be allowed, but isn't.", allowRecipient.contains("janko@evolveum.eu")); } diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java index 378e5ba532f..1a3d9be1c5f 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java @@ -129,7 +129,7 @@ public void test200ReportUserListScript() throws Exception { final String TEST_NAME = "test200ReportUserListScript"; if (!isOsUnix()) { - displaySkip(TEST_NAME); + displaySkip(); return; } diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java index bbb8bf2f4cd..a963dfcfa32 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java @@ -188,8 +188,8 @@ public void assertsAfterClockworkRun(CaseType rootCase, CaseType case0, List subcases, Task opTask, OperationResult result) throws Exception { ModelContext taskModelContext = miscHelper.getModelContext(rootCase, opTask, result); - IntegrationTestTools.display("model context from the root task", taskModelContext); -// assertEquals("Wrong # of projection contexts in root task", 1, taskModelContext.getProjectionContexts().size()); + PrismTestUtil.display("model context from the root task", taskModelContext); + // assertEquals("Wrong # of projection contexts in root task", 1, taskModelContext.getProjectionContexts().size()); // assertTrue("There are modifications in primary focus delta", ObjectDelta.isEmpty(taskModelContext.getFocusContext().getPrimaryDelta())); // assertTrue("There are modifications left in primary projection delta", // ObjectDelta.isEmpty( @@ -268,8 +268,8 @@ public void assertsAfterClockworkRun(CaseType rootCase, CaseType case0, List subcases, Task opTask, OperationResult result) throws Exception { ModelContext taskModelContext = miscHelper.getModelContext(rootCase, opTask, result); - IntegrationTestTools.display("model context from the root task", taskModelContext); -// assertEquals("Wrong # of projection contexts in root task", 1, taskModelContext.getProjectionContexts().size()); + PrismTestUtil.display("model context from the root task", taskModelContext); + // assertEquals("Wrong # of projection contexts in root task", 1, taskModelContext.getProjectionContexts().size()); // assertTrue("There are modifications in primary focus delta", ObjectDelta.isEmpty(taskModelContext.getFocusContext().getPrimaryDelta())); // assertTrue("There are modifications left in primary projection delta", // ObjectDelta.isEmpty( @@ -306,7 +306,7 @@ public void test100AddJackToGuests() throws Exception { final String TEST_NAME = "test100AddJackToGuests"; Task modelTask = taskManager.createTaskInstance(TEST_NAME); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); modelTask.setOwner(repositoryService.getObject(UserType.class, USER_ADMINISTRATOR_OID, null, result)); LensContext context = createUserLensContext(); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/ManualResourceTest.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/ManualResourceTest.java index c5f514b3183..e09049727a7 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/ManualResourceTest.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/ManualResourceTest.java @@ -7,6 +7,23 @@ package com.evolveum.midpoint.wf.impl.other; +import static org.testng.AssertJUnit.*; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; @@ -19,26 +36,8 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.wf.impl.AbstractWfTest; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.testng.AssertJUnit.*; /** * This is an adaptation of model-intest manual resource test(s) aimed to verify workflow-related aspects @@ -47,16 +46,13 @@ * @author Radovan Semancik * @author mederly */ -@ContextConfiguration(locations = {"classpath:ctx-workflow-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-workflow-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class ManualResourceTest extends AbstractWfTest { private static final File TEST_DIR = new File("src/test/resources/manual/"); - @SuppressWarnings("unused") - private static final Trace LOGGER = TraceManager.getTrace(ManualResourceTest.class); - private static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); private static final File RESOURCE_MANUAL_FILE = new File(TEST_DIR, "resource-manual.xml"); @@ -115,12 +111,12 @@ protected File getSystemConfigurationFile() { private PrismObject createUserWill() throws SchemaException { PrismObject user = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class).instantiate(); user.asObjectable() - .name(USER_WILL_NAME) - .givenName(USER_WILL_GIVEN_NAME) - .familyName(USER_WILL_FAMILY_NAME) - .fullName(USER_WILL_FULL_NAME) - .beginActivation().administrativeStatus(ActivationStatusType.ENABLED).end() - .beginCredentials().beginPassword().beginValue().setClearValue(USER_WILL_PASSWORD_OLD); + .name(USER_WILL_NAME) + .givenName(USER_WILL_GIVEN_NAME) + .familyName(USER_WILL_FAMILY_NAME) + .fullName(USER_WILL_FULL_NAME) + .beginActivation().administrativeStatus(ActivationStatusType.ENABLED).end() + .beginCredentials().beginPassword().beginValue().setClearValue(USER_WILL_PASSWORD_OLD); return user; } @@ -247,35 +243,35 @@ public void test110CloseCaseAndRecomputeWill() throws Exception { private void assertAccountWillAfterAssign(String expectedFullName) throws Exception { ShadowAsserter shadowRepoAsserter = assertRepoShadow(accountWillOid) - .assertConception() - .pendingOperations() + .assertConception() + .pendingOperations() .singleOperation() - .assertId() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .delta() - .display() - .end() - .end() + .assertId() + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .delta() + .display() + .end() .end() - .attributes() + .end() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end() - .assertNoPassword(); + .assertNoPassword(); assertAttributeFromCache(shadowRepoAsserter, ATTR_FULLNAME_QNAME, expectedFullName); assertShadowActivationAdministrativeStatusFromCache(shadowRepoAsserter.getObject(), ActivationStatusType.ENABLED); - ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .assertConception() - .attributes() + ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .assertConception() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end() - .assertNoPassword() - .pendingOperations() + .assertNoPassword() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .end() + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .end() .end(); assertAttributeFromCache(shadowModelAsserter, ATTR_FULLNAME_QNAME, expectedFullName); assertShadowActivationAdministrativeStatusFromCache(shadowModelAsserter.getObject(), ActivationStatusType.ENABLED); @@ -295,40 +291,40 @@ private void assertWillCase(String expectedCaseState, PendingOperationType pendi private void assertWillAfterCreateCaseClosed() throws Exception { ShadowAsserter shadowRepoAsserter = assertRepoShadow(accountWillOid) - .pendingOperations() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) - .end() + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) .end() - .attributes() + .end() + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end(); assertAttributeFromCache(shadowRepoAsserter, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); assertShadowActivationAdministrativeStatusFromCache(shadowRepoAsserter, ActivationStatusType.ENABLED); ShadowAsserter shadowModelAsserter = assertModelShadow(accountWillOid) - .assertName(USER_WILL_NAME) - .assertKind(ShadowKindType.ACCOUNT) - .attributes() + .assertName(USER_WILL_NAME) + .assertKind(ShadowKindType.ACCOUNT) + .attributes() .assertValue(ATTR_USERNAME_QNAME, USER_WILL_NAME) .end(); shadowRepoAsserter - .assertLife(); + .assertLife(); shadowModelAsserter - .assertLife() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .attributes() + .assertLife() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .attributes() .assertValue(ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME) .end() - .pendingOperations() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) - .end() + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertCompletionTimestamp(accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd) + .end() .end(); assertAttributeFromBackingStore(shadowModelAsserter, ATTR_DESCRIPTION_QNAME); assertShadowPassword(shadowModelAsserter); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java index f1b5cbb5766..55b34782e0b 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java @@ -37,14 +37,9 @@ import com.evolveum.midpoint.test.AbstractIntegrationTest; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ReadCapabilityType; -/** - * @author Radovan Semancik - */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public abstract class AbstractProvisioningIntegrationTest extends AbstractIntegrationTest { @@ -53,8 +48,6 @@ public abstract class AbstractProvisioningIntegrationTest extends AbstractIntegr protected static final String CSV_CONNECTOR_TYPE = "com.evolveum.polygon.connector.csv.CsvConnector"; - private static final Trace LOGGER = TraceManager.getTrace(AbstractProvisioningIntegrationTest.class); - @Autowired protected ProvisioningService provisioningService; @Autowired protected SynchronizationServiceMock syncServiceMock; @@ -169,7 +162,7 @@ protected void rememberConnectorInstance(PrismObject resource) thr } protected void rememberConnectorInstance(ConnectorInstance currentConnectorInstance) { - LOGGER.debug("Remembering connector instance {}", currentConnectorInstance); + logger.debug("Remembering connector instance {}", currentConnectorInstance); lastConfiguredConnectorInstance = currentConnectorInstance; } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java index d35c3548e34..d0c04781bff 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java @@ -73,7 +73,7 @@ public void test001Connectors() throws Exception { @Test public void testListConnectors() throws Exception { - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); List> connectors = provisioningService.searchObjects(ConnectorType.class, null, null, null, result); assertNotNull(connectors); @@ -101,7 +101,7 @@ public void testSearchConnectorSimple() throws SchemaException { @Test public void testSearchConnectorAnd() throws SchemaException { - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ObjectQuery query = prismContext.queryFor(ConnectorType.class) .item(SchemaConstants.C_CONNECTOR_FRAMEWORK).eq(SchemaConstants.ICF_FRAMEWORK_URI) diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java index bda2790957b..b8813977f70 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java @@ -6,6 +6,21 @@ */ package com.evolveum.midpoint.provisioning.impl; +import static org.testng.AssertJUnit.*; + +import java.io.File; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismAsserts; @@ -21,8 +36,6 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -30,21 +43,6 @@ import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PasswordCapabilityType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.File; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.List; - -import static org.testng.AssertJUnit.*; - /** * @author Radovan Semancik */ @@ -63,8 +61,6 @@ public class TestDBTable extends AbstractIntegrationTest { private static final String ACCOUNT_WILL_PASSWORD = "3lizab3th"; private static final String DB_TABLE_CONNECTOR_TYPE = "org.identityconnectors.databasetable.DatabaseTableConnector"; - private static final Trace LOGGER = TraceManager.getTrace(TestDBTable.class); - private static DerbyController derbyController = new DerbyController(); @Autowired @@ -80,31 +76,30 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @BeforeClass - public static void startDb() throws Exception { - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("START: ProvisioningServiceImplDBTest"); - LOGGER.info("------------------------------------------------------------------------------"); + public void startDb() throws Exception { + logger.info("------------------------------------------------------------------------------"); + logger.info("START: ProvisioningServiceImplDBTest"); + logger.info("------------------------------------------------------------------------------"); derbyController.startCleanServer(); } @AfterClass - public static void stopDb() throws Exception { + public void stopDb() throws Exception { derbyController.stop(); - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("STOP: ProvisioningServiceImplDBTest"); - LOGGER.info("------------------------------------------------------------------------------"); + logger.info("------------------------------------------------------------------------------"); + logger.info("STOP: ProvisioningServiceImplDBTest"); + logger.info("------------------------------------------------------------------------------"); } - @Test public void test000Integrity() throws ObjectNotFoundException, SchemaException { - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result).asObjectable(); String connectorOid = resource.getConnectorRef().getOid(); ConnectorType connector = repositoryService.getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(connector); - display("DB Connector",connector); + display("DB Connector", connector); } @Test @@ -115,11 +110,11 @@ public void test001Connection() throws Exception { // WHEN OperationResult testResult = provisioningService.testResource(RESOURCE_DERBY_OID, task); - display("Test result",testResult); + display("Test result", testResult); TestUtil.assertSuccess("Test resource failed (result)", testResult); ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result).asObjectable(); - display("Resource after test",resource); + display("Resource after test", resource); display("Resource after test (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); List nativeCapabilities = resource.getCapabilities().getNative().getAny(); @@ -133,7 +128,7 @@ public void test001Connection() throws Exception { @Test public void test002AddAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ShadowType account = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); @@ -146,11 +141,11 @@ public void test002AddAccount() throws Exception { // THEN result.computeStatus(); - display("add object result",result); - TestUtil.assertSuccess("addObject has failed (result)",result); + display("add object result", result); + TestUtil.assertSuccess("addObject has failed (result)", result); assertEquals(ACCOUNT_WILL_OID, addedObjectOid); - ShadowType accountType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result).asObjectable(); + ShadowType accountType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", ACCOUNT_WILL_USERNAME, accountType.getName()); // assertEquals("will", accountType.getName()); @@ -165,21 +160,21 @@ public void test002AddAccount() throws Exception { stmt.execute("select * from users"); ResultSet rs = stmt.getResultSet(); - assertTrue("The \"users\" table is empty",rs.next()); - assertEquals(ACCOUNT_WILL_USERNAME,rs.getString(DerbyController.COLUMN_LOGIN)); - assertEquals(ACCOUNT_WILL_PASSWORD,rs.getString(DerbyController.COLUMN_PASSWORD)); - assertEquals(ACCOUNT_WILL_FULLNAME,rs.getString(DerbyController.COLUMN_FULL_NAME)); + assertTrue("The \"users\" table is empty", rs.next()); + assertEquals(ACCOUNT_WILL_USERNAME, rs.getString(DerbyController.COLUMN_LOGIN)); + assertEquals(ACCOUNT_WILL_PASSWORD, rs.getString(DerbyController.COLUMN_PASSWORD)); + assertEquals(ACCOUNT_WILL_FULLNAME, rs.getString(DerbyController.COLUMN_FULL_NAME)); - assertFalse("The \"users\" table has more than one record",rs.next()); + assertFalse("The \"users\" table has more than one record", rs.next()); rs.close(); stmt.close(); } // MID-1234 - @Test(enabled=false) + @Test(enabled = false) public void test005GetAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); Task task = taskManager.createTaskInstance(); // WHEN @@ -201,5 +196,4 @@ public void test005GetAccount() throws Exception { assertEquals("Wrong password", ACCOUNT_WILL_PASSWORD, clearPassword); } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/async/TestAsyncUpdate.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/async/TestAsyncUpdate.java index 4504afa7469..c067b3ed3e7 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/async/TestAsyncUpdate.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/async/TestAsyncUpdate.java @@ -31,8 +31,6 @@ import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -81,9 +79,6 @@ public abstract class TestAsyncUpdate extends AbstractProvisioningIntegrationTes static final String ASYNC_CONNECTOR_TYPE = "AsyncUpdateConnector"; - @SuppressWarnings("unused") - private static final Trace LOGGER = TraceManager.getTrace(TestAsyncUpdate.class); - private static final String ATTR_TEST = "test"; private static final String ATTR_MEMBER_OF = "memberOf"; @@ -189,7 +184,7 @@ public void test004Configuration() throws Exception { PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertNotNull("No configuration container", configurationContainer); - PrismContainerDefinition confContDef = configurationContainer.getDefinition(); + PrismContainerDefinition confContDef = configurationContainer.getDefinition(); assertNotNull("No configuration container definition", confContDef); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java index b9c3d2b2fbb..dc32b967ac3 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java @@ -101,7 +101,7 @@ public void test000Integrity() throws Exception { assertNotNull("Resource is null", resource); assertNotNull("ResourceType is null", resourceType); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ResourceType resource = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result).asObjectable(); @@ -231,7 +231,7 @@ public void test005ParsedSchema() throws Exception { @Test public void test006Capabilities() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN ResourceType resource = provisioningService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java index 9e634b4970e..812c27960f0 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java @@ -20,8 +20,6 @@ import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** @@ -36,7 +34,7 @@ public class TestCsvGuid extends AbstractCsvTest { private static final File RESOURCE_CSV_GUID_FILE = new File(TEST_DIR, "resource-csv-guid.xml"); private static final String RESOURCE_CSV_GUID_OID = "b39e0b10-2449-11e7-b0c1-73f52bb2a496"; - private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-guid.xml");; + private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-guid.xml"); private static final String ACCOUNT_JACK_OID = "2db718b6-243a-11e7-a9e5-bbb2545f80ed"; private static final String ACCOUNT_JACK_GUID = "007"; private static final String ACCOUNT_JACK_UNAME = "jack"; @@ -49,8 +47,6 @@ public class TestCsvGuid extends AbstractCsvTest { protected static final String ATTR_UNAME = "uname"; protected static final QName ATTR_UNAME_QNAME = new QName(RESOURCE_NS, ATTR_UNAME); - private static final Trace LOGGER = TraceManager.getTrace(TestCsvGuid.class); - @Override protected File getResourceFile() { return RESOURCE_CSV_GUID_FILE; diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java index 4238e4ed075..ad7bae8e32c 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java @@ -19,8 +19,6 @@ import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** @@ -35,7 +33,7 @@ public class TestCsvUsername extends AbstractCsvTest { private static final File RESOURCE_CSV_USERNAME_FILE = new File(TEST_DIR, "resource-csv-username.xml"); private static final String RESOURCE_CSV_USERNAME_OID = "ef2bc95b-76e0-59e2-86d6-9999cccccccc"; - private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-username.xml");; + private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-username.xml"); private static final String ACCOUNT_JACK_OID = "2db718b6-243a-11e7-a9e5-bbb2545f80ed"; private static final String ACCOUNT_JACK_USERNAME = "jack"; @@ -44,8 +42,6 @@ public class TestCsvUsername extends AbstractCsvTest { protected static final String ATTR_USERNAME = "username"; protected static final QName ATTR_USERNAME_QNAME = new QName(RESOURCE_NS, ATTR_USERNAME); - private static final Trace LOGGER = TraceManager.getTrace(TestCsvUsername.class); - @Override protected File getResourceFile() { return RESOURCE_CSV_USERNAME_FILE; diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java index d7b61005b2c..c99f5912652 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java @@ -116,7 +116,7 @@ public void test000Integrity() throws Exception { assertNotNull("Resource is null", resource); assertNotNull("ResourceType is null", resourceType); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result) .asObjectable(); @@ -140,7 +140,7 @@ public void test000Integrity() throws Exception { @Test public void test010ListConnectors() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN List> connectors = repositoryService.searchObjects(ConnectorType.class, @@ -186,7 +186,7 @@ public void test010ListConnectors() throws Exception { @Test public void test012ConnectorRediscovery() { given(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); when(); Set discoverLocalConnectors = connectorManager.discoverLocalConnectors(result); @@ -354,7 +354,7 @@ protected void assertResourceAfterTest() { @Test public void test021Configuration() throws Exception { given(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); when(); resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); @@ -534,7 +534,7 @@ public void test024ParsedSchemaAgain() throws Exception { @Test public void test028Capabilities() throws Exception { given(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); when(); PrismObject resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); @@ -664,7 +664,7 @@ protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCr @Test public void test029CapabilitiesRepo() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); @@ -763,7 +763,7 @@ public void test030ResourceAndConnectorCachingTestConnection() throws Exception @Test public void test032ResourceAndConnectorCaching() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ConnectorInstance configuredConnectorInstance = resourceManager.getConfiguredConnectorInstance( resource, ReadCapabilityType.class, false, result); assertNotNull("No configuredConnectorInstance", configuredConnectorInstance); @@ -821,7 +821,7 @@ public void test032ResourceAndConnectorCaching() throws Exception { assertTrue("Connector instance was not cached", configuredConnectorInstance == configuredConnectorInstanceAgain); // Check if the connector still works. - OperationResult testResult = createOperationalResult("test"); + OperationResult testResult = createOperationResult("test"); configuredConnectorInstanceAgain.test(testResult); testResult.computeStatus(); TestUtil.assertSuccess("Connector test failed", testResult); @@ -877,7 +877,7 @@ public void test034ResourceAndConnectorCachingForceFresh() throws Exception { assertTrue("Connector instance was changed", configuredConnectorInstance == configuredConnectorInstanceAgain); // Check if the connector still works - OperationResult testResult = createOperationalResult("test"); + OperationResult testResult = createOperationResult("test"); configuredConnectorInstanceAgain.test(testResult); testResult.computeStatus(); TestUtil.assertSuccess("Connector test failed", testResult); @@ -1222,7 +1222,7 @@ protected void checkRepoAccountShadowWill(PrismObject accountRepo, X @Test public void test102GetAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); @@ -1260,7 +1260,7 @@ public void test102GetAccount() throws Exception { @Test public void test103GetAccountNoFetch() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); GetOperationOptions rootOptions = new GetOperationOptions(); @@ -1321,7 +1321,7 @@ public void test105ApplyDefinitionModifyDelta() throws Exception { @Test public void test106GetModifiedAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java index 36b03b41744..b1e06c992aa 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java @@ -6,36 +6,26 @@ */ package com.evolveum.midpoint.provisioning.impl.dummy; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.io.FileNotFoundException; -import java.io.IOException; import java.net.ConnectException; import java.util.Collection; import java.util.List; import java.util.Set; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.beans.factory.annotation.Autowired; import com.evolveum.icf.dummy.connector.DummyConnector; -import com.evolveum.icf.dummy.resource.ConflictException; -import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.icf.dummy.resource.DummyGroup; -import com.evolveum.icf.dummy.resource.DummyObject; -import com.evolveum.icf.dummy.resource.DummyPrivilege; -import com.evolveum.icf.dummy.resource.DummyResource; -import com.evolveum.icf.dummy.resource.SchemaViolationException; +import com.evolveum.icf.dummy.resource.*; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.match.MatchingRule; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; @@ -53,19 +43,12 @@ import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.DummyAccountAsserter; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** * @author semancik - * */ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationTest { @@ -123,7 +106,7 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected static final String GROUP_PIRATES_OID = "c0c010c0-d34d-b44f-f11d-3332eeee0000"; protected static final String GROUP_PIRATES_NAME = "pirates"; - protected static final File PRIVILEGE_PILLAGE_FILE = new File (TEST_DIR, "privilege-pillage.xml"); + protected static final File PRIVILEGE_PILLAGE_FILE = new File(TEST_DIR, "privilege-pillage.xml"); protected static final String PRIVILEGE_PILLAGE_OID = "c0c010c0-d34d-b44f-f11d-3332eeff0000"; protected static final String PRIVILEGE_PILLAGE_NAME = "pillage"; @@ -142,10 +125,8 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected static final String NOT_PRESENT_OID = "deaddead-dead-dead-dead-deaddeaddead"; - protected static final String OBJECTCLAS_GROUP_LOCAL_NAME = "GroupObjectClass"; - protected static final String OBJECTCLAS_PRIVILEGE_LOCAL_NAME = "CustomprivilegeObjectClass"; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractDummyTest.class); + protected static final String OBJECTCLASS_GROUP_LOCAL_NAME = "GroupObjectClass"; + protected static final String OBJECTCLASS_PRIVILEGE_LOCAL_NAME = "CustomprivilegeObjectClass"; protected static final QName ASSOCIATION_GROUP_NAME = new QName(RESOURCE_DUMMY_NS, "group"); protected static final QName ASSOCIATION_PRIV_NAME = new QName(RESOURCE_DUMMY_NS, "priv"); @@ -157,7 +138,7 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected String accountWillCurrentPassword = ACCOUNT_WILL_PASSWORD; - @Autowired(required = true) + @Autowired protected ProvisioningContextFactory provisioningContextFactory; protected String daemonIcfUid; @@ -200,7 +181,7 @@ protected String getDummyConnectorType() { } protected Class getDummyConnectorClass() { - return DummyConnector.class; + return DummyConnector.class; } protected void extraDummyResourceInit() throws Exception { @@ -247,7 +228,7 @@ protected boolean supportsActivation() { } protected void checkUniqueness(Collection> shadows) throws SchemaException { - for (PrismObject shadow: shadows) { + for (PrismObject shadow : shadows) { checkUniqueness(shadow); } } @@ -259,7 +240,7 @@ protected void checkUniqueness(PrismObject object) throws PrismPropertyDefinition itemDef = ShadowUtil.getAttributesContainer(object).getDefinition().findAttributeDefinition(SchemaConstants.ICFS_NAME); - LOGGER.info("item definition: {}", itemDef.debugDump()); + logger.info("item definition: {}", itemDef.debugDump()); //TODO: matching rule ObjectQuery query = prismContext.queryFor(ShadowType.class) .itemWithDef(itemDef, ShadowType.F_ATTRIBUTES, itemDef.getItemName()).eq(getWillRepoIcfName()) @@ -273,7 +254,6 @@ protected void checkUniqueness(PrismObject object) throws List> objects = repositoryService.searchObjects(ShadowType.class, query, null, result); - assertEquals("Wrong number of repo shadows for ICF NAME \"" + getWillRepoIcfName() + "\"", 1, objects.size()); } @@ -286,11 +266,13 @@ protected void assertAttribute(PrismObject shadow, QName attrNam assertAttribute(shadow.asObjectable(), attrName, expectedValues); } - protected void assertAttribute(PrismObject shadow, MatchingRule matchingRule, QName attrName, T... expectedValues) throws SchemaException { + protected void assertAttribute(PrismObject shadow, + MatchingRule matchingRule, QName attrName, T... expectedValues) + throws SchemaException { assertAttribute(resource, shadow.asObjectable(), matchingRule, attrName, expectedValues); } - protected void assertNoAttribute(PrismObject shadow, String attrName) { + protected void assertNoAttribute(PrismObject shadow, String attrName) { assertNoAttribute(resource, shadow.asObjectable(), attrName); } @@ -302,7 +284,7 @@ protected DummyAccount getDummyAccount(String icfName, String icfUid) throws Con if (isIcfNameUidSame()) { return dummyResource.getAccountByUsername(icfName); } else { - return dummyResource.getAccountById(icfUid); + return dummyResource.getAccountById(icfUid); } } @@ -310,14 +292,16 @@ protected DummyAccount getDummyAccountAssert(String icfName, String icfUid) thro if (isIcfNameUidSame()) { return dummyResource.getAccountByUsername(icfName); } else { - DummyAccount account = dummyResource.getAccountById(icfUid); - assertNotNull("No dummy account with ICF UID "+icfUid+" (expected name "+icfName+")", account); - assertEquals("Unexpected name in "+account, icfName, account.getName()); - return account; + DummyAccount account = dummyResource.getAccountById(icfUid); + assertNotNull("No dummy account with ICF UID " + icfUid + " (expected name " + icfName + ")", account); + assertEquals("Unexpected name in " + account, icfName, account.getName()); + return account; } } - protected DummyAccountAsserter assertDummyAccount(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, InterruptedException { + protected DummyAccountAsserter assertDummyAccount(String icfName, String icfUid) + throws ConnectException, FileNotFoundException, SchemaViolationException, + ConflictException, InterruptedException { if (isIcfNameUidSame()) { return dummyResourceCtl.assertAccountByUsername(icfName); } else { @@ -332,7 +316,7 @@ protected void assertNoDummyAccount(String icfName, String icfUid) throws Connec } else { account = dummyResource.getAccountById(icfUid); } - assertNull("Unexpected dummy account with ICF UID "+icfUid+" (name "+icfName+")", account); + assertNull("Unexpected dummy account with ICF UID " + icfUid + " (name " + icfName + ")", account); } protected DummyGroup getDummyGroup(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, InterruptedException { @@ -340,7 +324,7 @@ protected DummyGroup getDummyGroup(String icfName, String icfUid) throws Connect if (isIcfNameUidSame()) { return dummyResource.getGroupByName(icfName); } else { - return dummyResource.getGroupById(icfUid); + return dummyResource.getGroupById(icfUid); } } @@ -349,10 +333,10 @@ protected DummyGroup getDummyGroupAssert(String icfName, String icfUid) throws C if (isIcfNameUidSame()) { return dummyResource.getGroupByName(icfName); } else { - DummyGroup group = dummyResource.getGroupById(icfUid); - assertNotNull("No dummy group with ICF UID "+icfUid+" (expected name "+icfName+")", group); - assertEquals("Unexpected name in "+group, icfName, group.getName()); - return group; + DummyGroup group = dummyResource.getGroupById(icfUid); + assertNotNull("No dummy group with ICF UID " + icfUid + " (expected name " + icfName + ")", group); + assertEquals("Unexpected name in " + group, icfName, group.getName()); + return group; } } @@ -361,7 +345,7 @@ protected DummyPrivilege getDummyPrivilege(String icfName, String icfUid) throws if (isIcfNameUidSame()) { return dummyResource.getPrivilegeByName(icfName); } else { - return dummyResource.getPrivilegeById(icfUid); + return dummyResource.getPrivilegeById(icfUid); } } @@ -370,28 +354,29 @@ protected DummyPrivilege getDummyPrivilegeAssert(String icfName, String icfUid) if (isIcfNameUidSame()) { return dummyResource.getPrivilegeByName(icfName); } else { - DummyPrivilege priv = dummyResource.getPrivilegeById(icfUid); - assertNotNull("No dummy privilege with ICF UID "+icfUid+" (expected name "+icfName+")", priv); - assertEquals("Unexpected name in "+priv, icfName, priv.getName()); - return priv; + DummyPrivilege priv = dummyResource.getPrivilegeById(icfUid); + assertNotNull("No dummy privilege with ICF UID " + icfUid + " (expected name " + icfName + ")", priv); + assertEquals("Unexpected name in " + priv, icfName, priv.getName()); + return priv; } } protected void assertDummyAccountAttributeValues(String accountName, String accountUid, String attributeName, T... expectedValues) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, InterruptedException { DummyAccount dummyAccount = getDummyAccountAssert(accountName, accountUid); - assertNotNull("No account '"+accountName+"'", dummyAccount); + assertNotNull("No account '" + accountName + "'", dummyAccount); assertDummyAttributeValues(dummyAccount, attributeName, expectedValues); } - protected void assertDummyAttributeValues(DummyObject object, String attributeName, T... expectedValues) { + protected void assertDummyAttributeValues( + DummyObject object, String attributeName, T... expectedValues) { Set attributeValues = (Set) object.getAttributeValues(attributeName, expectedValues[0].getClass()); - assertNotNull("No attribute "+attributeName+" in "+object.getShortTypeName()+" "+object, attributeValues); - TestUtil.assertSetEquals("Wrong values of attribute "+attributeName+" in "+object.getShortTypeName()+" "+object, attributeValues, expectedValues); + assertNotNull("No attribute " + attributeName + " in " + object.getShortTypeName() + " " + object, attributeValues); + TestUtil.assertSetEquals("Wrong values of attribute " + attributeName + " in " + object.getShortTypeName() + " " + object, attributeValues, expectedValues); } protected void assertNoDummyAttribute(DummyObject object, String attributeName) { Set attributeValues = object.getAttributeValues(attributeName, Object.class); - assertNotNull("Unexpected attribute "+attributeName+" in "+object.getShortTypeName()+" "+object+": "+attributeValues, attributeValues); + assertNotNull("Unexpected attribute " + attributeName + " in " + object.getShortTypeName() + " " + object + ": " + attributeValues, attributeValues); } protected String getWillRepoIcfName() { @@ -426,7 +411,9 @@ protected void checkRepoAccountShadow(PrismObject shadowFromRepo) { ProvisioningTestUtil.checkRepoAccountShadow(shadowFromRepo); } - protected void assertDummyConnectorInstances(int expectedConnectorInstances) throws NumberFormatException, IOException, InterruptedException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertDummyConnectorInstances(int expectedConnectorInstances) + throws NumberFormatException, SchemaException, ObjectNotFoundException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { AbstractDummyTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java index 27545cf345d..cb21b2a2aae 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java @@ -2169,7 +2169,7 @@ private SearchResultMetadata testSeachIterative( ObjectFilter attrFilter, GetOperationOptions rootOptions, final boolean fullShadow, boolean useObjectClassFilter, final boolean useRepo, String... expectedAccountNames) throws Exception { - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ObjectQuery query; if (useObjectClassFilter) { @@ -2576,7 +2576,7 @@ public void test212GetPriv() throws Exception { } private void checkPrivPillage(PrismObject shadow, OperationResult result) throws SchemaException { - checkEntitlementShadow(shadow, result, OBJECTCLAS_PRIVILEGE_LOCAL_NAME, true); + checkEntitlementShadow(shadow, result, OBJECTCLASS_PRIVILEGE_LOCAL_NAME, true); assertShadowName(shadow, PRIVILEGE_PILLAGE_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ENTITLEMENT, shadow.asObjectable().getKind()); Collection> attributes = ShadowUtil.getAttributes(shadow); @@ -2647,7 +2647,7 @@ public void test214AddPrivilegeBargain() throws Exception { } private void checkPrivBargain(PrismObject shadow, OperationResult result) throws SchemaException { - checkEntitlementShadow(shadow, result, OBJECTCLAS_PRIVILEGE_LOCAL_NAME, true); + checkEntitlementShadow(shadow, result, OBJECTCLASS_PRIVILEGE_LOCAL_NAME, true); assertShadowName(shadow, PRIVILEGE_BARGAIN_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ENTITLEMENT, shadow.asObjectable().getKind()); Collection> attributes = ShadowUtil.getAttributes(shadow); @@ -2914,7 +2914,7 @@ public void test225GetFoolishPirateWill() throws Exception { assertDummyResourceGroupMembersReadCountIncrement(null, 0); - PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLAS_GROUP_LOCAL_NAME), "fools", resource, result); + PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLASS_GROUP_LOCAL_NAME), "fools", resource, result); assertNotNull("No shadow for group fools", foolsShadow); assertDummyResourceGroupMembersReadCountIncrement(null, 0); @@ -2974,7 +2974,7 @@ public void test226WillNonsensePrivilege() throws Exception { assertDummyResourceGroupMembersReadCountIncrement(null, 0); - PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLAS_GROUP_LOCAL_NAME), "fools", resource, result); + PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLASS_GROUP_LOCAL_NAME), "fools", resource, result); assertNotNull("No shadow for group fools", foolsShadow); assertDummyResourceGroupMembersReadCountIncrement(null, 0); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java index ac46a644ba7..e1b44754ee6 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java @@ -7,7 +7,6 @@ package com.evolveum.midpoint.provisioning.impl.dummy; import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; import java.io.File; @@ -16,12 +15,8 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; /** * The test of Provisioning service on the API level. The test is using dummy resource for speed and flexibility. @@ -39,11 +34,6 @@ public class TestDummyHacks extends TestDummy { private static final File CONNECTOR_DUMMY_FILE = new File(TEST_DIR, "connector-dummy.xml"); private static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); - private static final String RESOURCE_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-9999dddddddd"; - - private static final Trace LOGGER = TraceManager.getTrace(TestDummyHacks.class); - - private PrismObject connector; @Override protected File getResourceDummyFile() { @@ -61,7 +51,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // We want to avoid connector discovery and insert our own connector object // provisioningService.postInit(initResult); - connector = repoAddObjectFromFile(CONNECTOR_DUMMY_FILE, initResult); + repoAddObjectFromFile(CONNECTOR_DUMMY_FILE, initResult); super.initSystem(initTask, initResult); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java index 7a56e106dd7..5aace10768e 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java @@ -65,7 +65,7 @@ public void test113GetResourceBrokenSchemaRuntime() throws Exception { public void testGetResourceBrokenSchema(BreakMode breakMode) throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // precondition PrismObject repoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java index b0a269c8174..b13e941940d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java @@ -674,11 +674,11 @@ private ObjectQuery createGroupNameQuery(String groupName) throws SchemaExceptio ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery( RESOURCE_DUMMY_OID, - new QName(ResourceTypeUtil.getResourceNamespace(resourceType), OBJECTCLAS_GROUP_LOCAL_NAME), + new QName(ResourceTypeUtil.getResourceNamespace(resourceType), OBJECTCLASS_GROUP_LOCAL_NAME), prismContext); ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); - ObjectClassComplexTypeDefinition objectClassDef = resourceSchema.findObjectClassDefinition(OBJECTCLAS_GROUP_LOCAL_NAME); + ObjectClassComplexTypeDefinition objectClassDef = resourceSchema.findObjectClassDefinition(OBJECTCLASS_GROUP_LOCAL_NAME); ResourceAttributeDefinition attrDef = objectClassDef.findAttributeDefinition(SchemaConstants.ICFS_NAME); ObjectFilter nameFilter = prismContext.queryFor(ShadowType.class) .itemWithDef(attrDef, ShadowType.F_ATTRIBUTES, attrDef.getItemName()).eq(groupName) diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplaceLegacyUpdate.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplaceLegacyUpdate.java index 1ab48c75bcf..5a4d6fd2115 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplaceLegacyUpdate.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplaceLegacyUpdate.java @@ -12,8 +12,6 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Listeners; @@ -33,8 +31,6 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestDummyPrioritiesAndReadReplaceLegacyUpdate extends TestDummyPrioritiesAndReadReplace { - private static final Trace LOGGER = TraceManager.getTrace(TestDummyPrioritiesAndReadReplaceLegacyUpdate.class); - public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy-legacy-update.xml"); @Override diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java index adb7fa38a6e..605b7e58cbf 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java @@ -41,8 +41,6 @@ import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -58,8 +56,6 @@ @DirtiesContext public class TestDummyResourceAndSchemaCaching extends AbstractDummyTest { - private static final Trace LOGGER = TraceManager.getTrace(TestDummyResourceAndSchemaCaching.class); - @Test public void test010GetResource() throws Exception { final String TEST_NAME = "test010GetResource"; diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java index c5058f036eb..228422bf1bb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java @@ -236,7 +236,7 @@ public void test005ParsedSchemaSchemaless() throws Exception { @Test public void test006GetObjectSchemaless() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); PrismObject resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_NO_SCHEMA_OID, null, null, result); assertNotNull("Resource is null", resource); ResourceType resourceType = resource.asObjectable(); @@ -547,7 +547,7 @@ public void test105ParsedSchemaStaticSchema() throws Exception { @Test public void test106GetObjectStaticSchema() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); PrismObject resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_STATIC_SCHEMA_OID, null, null, result); assertNotNull("Resource is null", resource); @@ -734,7 +734,7 @@ public void test107Capabilities() throws Exception { @Test public void test200AddAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ShadowType account = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); account.asPrismObject().checkConsistence(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java index d9a6e47601e..c9083560523 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java @@ -198,7 +198,7 @@ public void test210ModifyAccountQuote() throws Exception { @Test public void test300GetAccount() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, result); @@ -220,7 +220,7 @@ public void test300GetAccount() throws Exception { @Test public void test310SearchAllShadows() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java index 9e54daa18f9..a475d829cb6 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java @@ -160,7 +160,7 @@ public void test000Sanity() throws Exception { assertNotNull("Resource is null", resource); assertNotNull("ResourceType is null", resourceType); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ResourceType repoResource = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result).asObjectable(); @@ -230,7 +230,7 @@ public void test003Connection() throws Exception { @Test public void test004Configuration() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN resource = provisioningService.getObject(ResourceType.class, getResourceOid(), null, null, result); @@ -299,7 +299,7 @@ protected int getNumberOfAccountAttributeDefinitions() { @Test public void test006Capabilities() throws Exception { // GIVEN - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); // WHEN ResourceType resource = provisioningService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java index 7dc1696d757..f7fa0750982 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java @@ -17,9 +17,6 @@ import java.util.List; import java.util.stream.Collectors; -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; - import org.apache.commons.io.FileUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -30,14 +27,11 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.crypto.EncryptionException; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -53,11 +47,6 @@ public class TestSemiManual extends AbstractManualResourceTest { private static final File CSV_SOURCE_FILE = new File(TEST_DIR, "semi-manual.csv"); private static final File CSV_TARGET_FILE = new File("target/semi-manual.csv"); - private static final Trace LOGGER = TraceManager.getTrace(TestSemiManual.class); - - protected static final String ATTR_DISABLED = "disabled"; - protected static final QName ATTR_DISABLED_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DISABLED); - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -79,7 +68,7 @@ protected boolean supportsBackingStore() { } protected PrismObject addResource(OperationResult result) - throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { + throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { PrismObject resource = prismContext.parseObject(getResourceFile()); fillInConnectorRef(resource, MANUAL_CONNECTOR_TYPE, result); fillInAdditionalConnectorRef(resource, "csv", CSV_CONNECTOR_TYPE, result); @@ -102,7 +91,7 @@ protected int getNumberOfAccountAttributeDefinitions() { @Override protected void backingStoreAddWill() throws IOException { - appendToCsv(new String[]{ACCOUNT_WILL_USERNAME, ACCOUNT_WILL_FULLNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL, "", "false", ACCOUNT_WILL_PASSWORD_OLD}); + appendToCsv(new String[] { ACCOUNT_WILL_USERNAME, ACCOUNT_WILL_FULLNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL, "", "false", ACCOUNT_WILL_PASSWORD_OLD }); } @Override @@ -113,7 +102,7 @@ protected void backingStoreUpdateWill(String newFullName, ActivationStatusType n } else { disabled = "true"; } - replaceInCsv(new String[]{ACCOUNT_WILL_USERNAME, newFullName, ACCOUNT_WILL_DESCRIPTION_MANUAL, "", disabled, password}); + replaceInCsv(new String[] { ACCOUNT_WILL_USERNAME, newFullName, ACCOUNT_WILL_DESCRIPTION_MANUAL, "", disabled, password }); } private void appendToCsv(String[] data) throws IOException { @@ -126,7 +115,7 @@ private void replaceInCsv(String[] data) throws IOException { for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] cols = line.split(","); - if (cols[0].matches("\""+data[0]+"\"")) { + if (cols[0].matches("\"" + data[0] + "\"")) { lines.set(i, formatCsvLine(data)); } } @@ -134,13 +123,13 @@ private void replaceInCsv(String[] data) throws IOException { } private String formatCsvLine(String[] data) { - return Arrays.stream(data).map(s -> "\""+s+"\"").collect(Collectors.joining(",")); + return Arrays.stream(data).map(s -> "\"" + s + "\"").collect(Collectors.joining(",")); } @Override protected void assertShadowPassword(PrismObject shadow) { // CSV password is readable PrismProperty passValProp = shadow.findProperty(SchemaConstants.PATH_PASSWORD_VALUE); - assertNotNull("No password value property in "+shadow+": "+passValProp, passValProp); + assertNotNull("No password value property in " + shadow + ": " + passValProp, passValProp); } } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/ResourceObjectShadowChangeDescriptionAsserter.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/ResourceObjectShadowChangeDescriptionAsserter.java index 534c8a20421..03f4e121ba6 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/ResourceObjectShadowChangeDescriptionAsserter.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/ResourceObjectShadowChangeDescriptionAsserter.java @@ -12,8 +12,8 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.api.ResourceObjectShadowChangeDescription; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.test.asserter.prism.ObjectDeltaAsserter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -30,7 +30,7 @@ public ResourceObjectShadowChangeDescriptionAsserter(ResourceObjectShadowChangeD } public ResourceObjectShadowChangeDescriptionAsserter display() { - IntegrationTestTools.display("Change notification", changeDesc); + PrismTestUtil.display("Change notification", changeDesc); return this; } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/SynchronizationServiceMock.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/SynchronizationServiceMock.java index a3d8e36d006..8438c47129d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/SynchronizationServiceMock.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/mock/SynchronizationServiceMock.java @@ -40,7 +40,8 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @Service(value = "syncServiceMock") -public class SynchronizationServiceMock implements ResourceObjectChangeListener, ResourceOperationListener { +public class SynchronizationServiceMock + implements ResourceObjectChangeListener, ResourceOperationListener { private static final Trace LOGGER = TraceManager.getTrace(SynchronizationServiceMock.class); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java index 5e34f210be5..0dd51bf3aa0 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java @@ -28,16 +28,10 @@ import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -/** - * @author semancik - * - */ public abstract class AbstractOpenDjTest extends AbstractProvisioningIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources/opendj"); @@ -159,25 +153,23 @@ public abstract class AbstractOpenDjTest extends AbstractProvisioningIntegration protected static final QName ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NS, "group"); - private static final Trace LOGGER = TraceManager.getTrace(AbstractOpenDjTest.class); - protected MatchingRule dnMatchingRule; protected PrismObject resource; protected ResourceType resourceType; protected PrismObject connector; - @Autowired(required = true) + @Autowired protected ProvisioningService provisioningService; // Used to make sure that the connector is cached - @Autowired(required = true) + @Autowired protected ResourceManager resourceManager; - @Autowired(required = true) + @Autowired protected SynchronizationServiceMock syncServiceMock; - @Autowired(required = true) + @Autowired protected MatchingRuleRegistry matchingRuleRegistry; protected File getResourceOpenDjFile() { diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java index ac1590ab088..14bb5b5ff9d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java @@ -69,10 +69,7 @@ import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; -import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ScriptCapabilityType.Host; @@ -82,14 +79,14 @@ /** * Test for provisioning service implementation. - * + *

* This test will initialize mock repository and fill-in some test data. The * "default" repository objects cannot be used, as the new provisioning service * implementation assumes a slightly different connector configuration that was * used in the OpenIDM. - * + *

* This test will initialize embedded OpenDJ as a target resource. - * + *

* The test calls the new Provisioning Service Interface (java). No WSDL mess. * * @author Radovan Semancik @@ -105,19 +102,19 @@ public class TestOpenDj extends AbstractOpenDjTest { private static final String[] JACK_FULL_NAME_LANG_EN_SK = { "en", "Jack Sparrow", "sk", "Džek Sperou" - }; + }; private static final String[] JACK_FULL_NAME_LANG_EN_SK_RU_HR = { "en", "Jack Sparrow", "sk", "Džek Sperou", "ru", "Джек Воробей", "hr", "Ðek Sperou" - }; + }; private static final String[] JACK_FULL_NAME_LANG_CZ_HR = { "cz", "Džek Sperou", "hr", "Ðek Sperou" - }; + }; protected static final String USER_JACK_FULL_NAME_CAPTAIN = "Captain Jack Sparrow"; @@ -125,9 +122,7 @@ public class TestOpenDj extends AbstractOpenDjTest { "en", "Captain Jack Sparrow", "cz", "Kapitán Džek Sperou", "sk", "Kapitán Džek Sperou" - }; - - private static final Trace LOGGER = TraceManager.getTrace(TestOpenDj.class); + }; private String groupSailorOid; @@ -139,32 +134,32 @@ protected int getNumberOfBaseContextShadows() { } @BeforeClass - public static void startLdap() throws Exception { - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("START: ProvisioningServiceImplOpenDJTest"); - LOGGER.info("------------------------------------------------------------------------------"); + public void startLdap() throws Exception { + logger.info("------------------------------------------------------------------------------"); + logger.info("START: ProvisioningServiceImplOpenDJTest"); + logger.info("------------------------------------------------------------------------------"); try { openDJController.startCleanServer(); openDJController.addEntry("dn: ou=specialgroups,dc=example,dc=com\n" + "objectclass: organizationalUnit\n" + "ou: specialgroups\n"); } catch (IOException ex) { - LOGGER.error("Couldn't start LDAP.", ex); + logger.error("Couldn't start LDAP.", ex); throw ex; } } @AfterClass - public static void stopLdap() { + public void stopLdap() { openDJController.stop(); - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("STOP: ProvisioningServiceImplOpenDJTest"); - LOGGER.info("------------------------------------------------------------------------------"); + logger.info("------------------------------------------------------------------------------"); + logger.info("STOP: ProvisioningServiceImplOpenDJTest"); + logger.info("------------------------------------------------------------------------------"); } /** * This should be the very first test that works with the resource. - * + *

* The original repository object does not have resource schema. The schema should be generated from * the resource on the first use. This is the test that executes testResource and checks whether the * schema was generated. @@ -173,40 +168,40 @@ public static void stopLdap() { public void test003Connection() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); - ResourceType resourceTypeBefore = repositoryService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, result).asObjectable(); - assertNotNull("No connector ref",resourceTypeBefore.getConnectorRef()); - assertNotNull("No connector ref OID",resourceTypeBefore.getConnectorRef().getOid()); + ResourceType resourceTypeBefore = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result).asObjectable(); + assertNotNull("No connector ref", resourceTypeBefore.getConnectorRef()); + assertNotNull("No connector ref OID", resourceTypeBefore.getConnectorRef().getOid()); connector = repositoryService.getObject(ConnectorType.class, resourceTypeBefore.getConnectorRef().getOid(), null, result); ConnectorType connectorType = connector.asObjectable(); assertNotNull(connectorType); Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceTypeBefore); AssertJUnit.assertNull("Found schema before test connection. Bad test setup?", resourceXsdSchemaElementBefore); - OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); + OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); - display("Test connection result",operationResult); - TestUtil.assertSuccess("Test connection failed",operationResult); + display("Test connection result", operationResult); + TestUtil.assertSuccess("Test connection failed", operationResult); - PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, result); + PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); - display("Resource after testResource (repository)",resourceTypeRepoAfter); + display("Resource after testResource (repository)", resourceTypeRepoAfter); display("Resource after testResource (repository, XML)", PrismTestUtil.serializeObjectToString(resourceTypeRepoAfter.asPrismObject(), PrismContext.LANG_XML)); XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); - assertNotNull("No schema after test connection",xmlSchemaTypeAfter); + assertNotNull("No schema after test connection", xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); CachingMetadataType cachingMetadata = xmlSchemaTypeAfter.getCachingMetadata(); - assertNotNull("No caching metadata",cachingMetadata); - assertNotNull("No retrievalTimestamp",cachingMetadata.getRetrievalTimestamp()); - assertNotNull("No serialNumber",cachingMetadata.getSerialNumber()); + assertNotNull("No caching metadata", cachingMetadata); + assertNotNull("No retrievalTimestamp", cachingMetadata.getRetrievalTimestamp()); + assertNotNull("No serialNumber", cachingMetadata.getSerialNumber()); Element xsdElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); ResourceSchema parsedSchema = ResourceSchemaImpl.parse(xsdElement, resourceTypeRepoAfter.toString(), prismContext); - assertNotNull("No schema after parsing",parsedSchema); + assertNotNull("No schema after parsing", parsedSchema); Collection objectClasses = parsedSchema.getObjectClassDefinitions(); List objectClassesToGenerate = ResourceTypeUtil.getSchemaGenerationConstraints(resourceTypeRepoAfter); @@ -216,21 +211,19 @@ public void test003Connection() throws Exception { ObjectClassComplexTypeDefinition inetOrgPersonDefinition = parsedSchema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); assertNull("The _PASSSWORD_ attribute sneaked into schema", inetOrgPersonDefinition.findAttributeDefinition( - new QName(SchemaConstants.NS_ICF_SCHEMA,"password"))); + new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); assertNull("The userPassword attribute sneaked into schema", inetOrgPersonDefinition.findAttributeDefinition( - new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeRepoAfter),"userPassword"))); + new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeRepoAfter), "userPassword"))); assertShadows(1); } @Test public void test004ResourceAndConnectorCaching() throws Exception { - final String TEST_NAME = "test004ResourceAndConnectorCaching"; - Task task = getTestTask(); OperationResult result = task.getResult(); - resource = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, null, result); + resource = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, result); resourceType = resource.asObjectable(); ConnectorInstance configuredConnectorInstance = resourceManager.getConfiguredConnectorInstance( resource, ReadCapabilityType.class, false, result); @@ -239,12 +232,12 @@ public void test004ResourceAndConnectorCaching() throws Exception { assertNotNull("No resource schema", resourceSchema); // WHEN - PrismObject resourceAgain = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, task, result); + PrismObject resourceAgain = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); // THEN ResourceType resourceTypeAgain = resourceAgain.asObjectable(); - assertNotNull("No connector ref",resourceTypeAgain.getConnectorRef()); - assertNotNull("No connector ref OID",resourceTypeAgain.getConnectorRef().getOid()); + assertNotNull("No connector ref", resourceTypeAgain.getConnectorRef()); + assertNotNull("No connector ref OID", resourceTypeAgain.getConnectorRef().getOid()); PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); @@ -268,8 +261,6 @@ public void test004ResourceAndConnectorCaching() throws Exception { @Test public void test005Capabilities() throws Exception { - final String TEST_NAME = "test005Capabilities"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -283,16 +274,16 @@ public void test005Capabilities() throws Exception { CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); - assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); + assertFalse("Empty capabilities returned", nativeCapabilitiesList.isEmpty()); CredentialsCapabilityType capCred = CapabilityUtil.getCapability(nativeCapabilitiesList, CredentialsCapabilityType.class); - assertNotNull("credentials capability not found",capCred); + assertNotNull("credentials capability not found", capCred); PasswordCapabilityType capPassword = capCred.getPassword(); assertNotNull("password capability not present", capPassword); assertPasswordCapability(capPassword); // Connector cannot do activation, this should be null ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); - assertNull("Found activation capability while not expecting it" ,capAct); + assertNull("Found activation capability while not expecting it", capAct); ScriptCapabilityType capScript = CapabilityUtil.getCapability(nativeCapabilitiesList, ScriptCapabilityType.class); assertNotNull("No script capability", capScript); @@ -316,21 +307,20 @@ public void test005Capabilities() throws Exception { DeleteCapabilityType capDelete = CapabilityUtil.getCapability(nativeCapabilitiesList, DeleteCapabilityType.class); assertNotNull("No delete capability", capDelete); - List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { - System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); + System.out.println("Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class); - assertNotNull("credentials effective capability not found",capCred); - assertNotNull("password effective capability not found",capCred.getPassword()); + assertNotNull("credentials effective capability not found", capCred); + assertNotNull("password effective capability not found", capCred.getPassword()); // Although connector does not support activation, the resource specifies a way how to simulate it. // Therefore the following should succeed capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); - assertNotNull("activation capability not found",capAct); + assertNotNull("activation capability not found", capAct); - PagedSearchCapabilityType capPage = ResourceTypeUtil.getEffectiveCapability(resource, PagedSearchCapabilityType.class); + PagedSearchCapabilityType capPage = ResourceTypeUtil.getEffectiveCapability(resource, PagedSearchCapabilityType.class); assertNotNull("paged search capability not present", capPage); assertShadows(1); @@ -342,9 +332,6 @@ protected void assertPasswordCapability(PasswordCapabilityType capPassword) { @Test public void test006Schema() throws Exception { - final String TEST_NAME = "test006RefinedSchema"; - // GIVEN - // WHEN ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); display("Resource schema", resourceSchema); @@ -365,10 +352,9 @@ public void test006Schema() throws Exception { assertFalse("UID has update", idPrimaryDef.canModify()); assertTrue("No UID read", idPrimaryDef.canRead()); assertTrue("UID definition not in identifiers", accountDef.getPrimaryIdentifiers().contains(idPrimaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, idPrimaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, idPrimaryDef.getFrameworkAttributeName()); assertEquals("Wrong primary identifier matching rule", PrismConstants.UUID_MATCHING_RULE_NAME, idPrimaryDef.getMatchingRuleQName()); - ResourceAttributeDefinition idSecondaryDef = accountDef.findAttributeDefinition(getSecondaryIdentifierQName()); assertEquals(1, idSecondaryDef.getMaxOccurs()); assertEquals(1, idSecondaryDef.getMinOccurs()); @@ -376,7 +362,7 @@ public void test006Schema() throws Exception { assertTrue("No NAME update", idSecondaryDef.canModify()); assertTrue("No NAME read", idSecondaryDef.canRead()); assertTrue("NAME definition not in secondary identifiers", accountDef.getSecondaryIdentifiers().contains(idSecondaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, idSecondaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, idSecondaryDef.getFrameworkAttributeName()); assertEquals("Wrong secondary identifier matching rule", PrismConstants.DISTINGUISHED_NAME_MATCHING_RULE_NAME, idSecondaryDef.getMatchingRuleQName()); ResourceAttributeDefinition cnDef = accountDef.findAttributeDefinition("cn"); @@ -484,7 +470,7 @@ public void test006Schema() throws Exception { assertFalse("UID has update", posixIdPrimaryDef.canModify()); assertTrue("No UID read", posixIdPrimaryDef.canRead()); assertTrue("UID definition not in identifiers", accountDef.getPrimaryIdentifiers().contains(posixIdPrimaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, posixIdPrimaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, posixIdPrimaryDef.getFrameworkAttributeName()); ResourceAttributeDefinition posixIdSecondaryDef = posixAccountDef.findAttributeDefinition(getSecondaryIdentifierQName()); assertEquals(1, posixIdSecondaryDef.getMaxOccurs()); @@ -493,7 +479,7 @@ public void test006Schema() throws Exception { assertTrue("No NAME update", posixIdSecondaryDef.canModify()); assertTrue("No NAME read", posixIdSecondaryDef.canRead()); assertTrue("NAME definition not in secondary identifiers", accountDef.getSecondaryIdentifiers().contains(posixIdSecondaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, posixIdSecondaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, posixIdSecondaryDef.getFrameworkAttributeName()); ObjectClassComplexTypeDefinition normalDef = resourceSchema.findObjectClassDefinition(new QName(RESOURCE_NS, "normalTestingObjectClass")); display("normalTestingObjectClass object class def", normalDef); @@ -519,11 +505,11 @@ public void test006Schema() throws Exception { } protected void assertTimestampType(String attrName, ResourceAttributeDefinition def) { - assertEquals("Wrong "+attrName+" type", DOMUtil.XSD_DATETIME, def.getTypeName()); + assertEquals("Wrong " + attrName + " type", DOMUtil.XSD_DATETIME, def.getTypeName()); } protected void assertPolyStringType(String attrName, ResourceAttributeDefinition def) { - assertEquals("Wrong "+attrName+" type", PolyStringType.COMPLEX_TYPE, def.getTypeName()); + assertEquals("Wrong " + attrName + " type", PolyStringType.COMPLEX_TYPE, def.getTypeName()); } @Test @@ -556,7 +542,7 @@ public void test007RefinedSchema() throws Exception { assertFalse("UID has update", idPrimaryDef.canModify()); assertTrue("No UID read", idPrimaryDef.canRead()); assertTrue("UID definition not in identifiers", accountDef.getPrimaryIdentifiers().contains(idPrimaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, idPrimaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, idPrimaryDef.getFrameworkAttributeName()); RefinedAttributeDefinition idSecondaryDef = accountDef.findAttributeDefinition(getSecondaryIdentifierQName()); assertEquals(1, idSecondaryDef.getMaxOccurs()); @@ -566,7 +552,7 @@ public void test007RefinedSchema() throws Exception { assertTrue("No NAME read", idSecondaryDef.canRead()); assertTrue("NAME definition not in identifiers", accountDef.getSecondaryIdentifiers().contains(idSecondaryDef)); assertEquals("Wrong NAME matching rule", PrismConstants.DISTINGUISHED_NAME_MATCHING_RULE_NAME, idSecondaryDef.getMatchingRuleQName()); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, idSecondaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, idSecondaryDef.getFrameworkAttributeName()); RefinedAttributeDefinition cnDef = accountDef.findAttributeDefinition("cn"); assertNotNull("No definition for cn", cnDef); @@ -625,7 +611,7 @@ public void test007RefinedSchema() throws Exception { assertFalse("UID has update", posixIdPrimaryDef.canModify()); assertTrue("No UID read", posixIdPrimaryDef.canRead()); assertTrue("UID definition not in identifiers", accountDef.getPrimaryIdentifiers().contains(posixIdPrimaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, posixIdPrimaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_UID_NAME, posixIdPrimaryDef.getFrameworkAttributeName()); RefinedAttributeDefinition posixIdSecondaryDef = posixAccountDef.findAttributeDefinition(getSecondaryIdentifierQName()); assertEquals(1, posixIdSecondaryDef.getMaxOccurs()); @@ -634,15 +620,13 @@ public void test007RefinedSchema() throws Exception { assertTrue("No NAME update", posixIdSecondaryDef.canModify()); assertTrue("No NAME read", posixIdSecondaryDef.canRead()); assertTrue("NAME definition not in secondary identifiers", accountDef.getSecondaryIdentifiers().contains(posixIdSecondaryDef)); - assertEquals("Wrong "+OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME+" frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, posixIdSecondaryDef.getFrameworkAttributeName()); + assertEquals("Wrong " + OpenDJController.RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME + " frameworkAttributeName", ProvisioningTestUtil.CONNID_NAME_NAME, posixIdSecondaryDef.getFrameworkAttributeName()); assertShadows(1); } - @Test public void test020ListResourceObjects() throws Exception { - final String TEST_NAME = "test020ListResourceObjects"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -653,17 +637,14 @@ public void test020ListResourceObjects() throws Exception { // THEN assertNotNull(objectList); - assertFalse("Empty list returned",objectList.isEmpty()); - display("Resource object list "+RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS,objectList); + assertFalse("Empty list returned", objectList.isEmpty()); + display("Resource object list " + RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, objectList); assertShadows(1 + getNumberOfBaseContextShadows()); } - @Test public void test110GetObject() throws Exception { - final String TEST_NAME = "test110GetObject"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -674,7 +655,6 @@ public void test110GetObject() throws Exception { String addedObjectOid = provisioningService.addObject(objectToAdd.asPrismObject(), null, null, task, result); assertEquals(ACCOUNT_JBOND_OID, addedObjectOid); - PropertyReferenceListType resolve = new PropertyReferenceListType(); // WHEN when(); @@ -696,9 +676,9 @@ public void test110GetObject() throws Exception { assertEquals(new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME), provisioningShadow.getObjectClass()); assertEquals(RESOURCE_OPENDJ_OID, provisioningShadow.getResourceRef().getOid()); String idPrimaryVal = getAttributeValue(provisioningShadow, getPrimaryIdentifierQName()); - assertNotNull("No primary identifier ("+getPrimaryIdentifierQName().getLocalPart()+")", idPrimaryVal); + assertNotNull("No primary identifier (" + getPrimaryIdentifierQName().getLocalPart() + ")", idPrimaryVal); String idSecondaryVal = getAttributeValue(provisioningShadow, getSecondaryIdentifierQName()); - assertNotNull("No secondary ("+getSecondaryIdentifierQName().getLocalPart()+")", idSecondaryVal); + assertNotNull("No secondary (" + getSecondaryIdentifierQName().getLocalPart() + ")", idSecondaryVal); // Capitalization is the same as returned by OpenDJ assertEquals("Wrong secondary identifier", "uid=jbond,ou=People,dc=example,dc=com", idSecondaryVal); assertEquals("Wrong LDAP uid", "jbond", getAttributeValue(provisioningShadow, new QName(resourceNamespace, "uid"))); @@ -716,9 +696,9 @@ public void test110GetObject() throws Exception { assertEquals(new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME), repoShadow.getObjectClass()); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); idPrimaryVal = getAttributeValue(repoShadow, getPrimaryIdentifierQName()); - assertNotNull("No primary identifier ("+getPrimaryIdentifierQName().getLocalPart()+") (repo)", idPrimaryVal); + assertNotNull("No primary identifier (" + getPrimaryIdentifierQName().getLocalPart() + ") (repo)", idPrimaryVal); idSecondaryVal = getAttributeValue(repoShadow, getSecondaryIdentifierQName()); - assertNotNull("No secondary ("+getSecondaryIdentifierQName().getLocalPart()+") (repo)", idSecondaryVal); + assertNotNull("No secondary (" + getSecondaryIdentifierQName().getLocalPart() + ") (repo)", idSecondaryVal); // must be all lowercase assertEquals("Wrong secondary identifier (repo)", "uid=jbond,ou=people,dc=example,dc=com", idSecondaryVal); @@ -727,12 +707,12 @@ public void test110GetObject() throws Exception { protected void assertTimestamp(String attrName, Object timestampValue) { if (!(timestampValue instanceof XMLGregorianCalendar)) { - fail("Wrong type of "+attrName+", expected XMLGregorianCalendar but was "+timestampValue.getClass()); + fail("Wrong type of " + attrName + ", expected XMLGregorianCalendar but was " + timestampValue.getClass()); } - assertBetween("Unreasonable date in "+attrName, + assertBetween("Unreasonable date in " + attrName, XmlTypeConverter.createXMLGregorianCalendar(1900, 1, 1, 0, 0, 0), XmlTypeConverter.createXMLGregorianCalendar(2200, 1, 1, 0, 0, 0), - (XMLGregorianCalendar)timestampValue); + (XMLGregorianCalendar) timestampValue); } protected void assertShadowPassword(ShadowType provisioningShadow) throws Exception { @@ -745,7 +725,7 @@ protected void assertShadowPassword(ShadowType provisioningShadow) throws Except return; } ProtectedStringType passwordValue = passwordType.getValue(); - assertNull("Unexpected password value in "+provisioningShadow+": "+passwordValue, passwordValue); + assertNull("Unexpected password value in " + provisioningShadow + ": " + passwordValue, passwordValue); } /** @@ -753,13 +733,11 @@ protected void assertShadowPassword(ShadowType provisioningShadow) throws Except */ @Test public void test111GetObjectNotFoundRepo() throws Exception { - final String TEST_NAME = "test111GetObjectNotFoundRepo"; - Task task = getTestTask(); OperationResult result = task.getResult(); try { - ObjectType object = provisioningService.getObject(ObjectType.class, NON_EXISTENT_OID, null, task, result).asObjectable(); + provisioningService.getObject(ObjectType.class, NON_EXISTENT_OID, null, task, result).asObjectable(); Assert.fail("Expected exception, but haven't got one"); } catch (ObjectNotFoundException e) { // This is expected @@ -772,9 +750,7 @@ public void test111GetObjectNotFoundRepo() throws Exception { assertFalse(result.hasUnknownStatus()); // TODO: check result - } catch (CommunicationException e) { - Assert.fail("Expected ObjectNotFoundException, but got" + e); - } catch (SchemaException e) { + } catch (CommunicationException | SchemaException e) { Assert.fail("Expected ObjectNotFoundException, but got" + e); } @@ -787,8 +763,6 @@ public void test111GetObjectNotFoundRepo() throws Exception { */ @Test public void test112GetObjectNotFoundResource() throws Exception { - final String TEST_NAME = "test112GetObjectNotFoundResource"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -800,26 +774,22 @@ public void test112GetObjectNotFoundResource() throws Exception { when(); ShadowAsserter.forShadow(shadow, "provisioning") - .assertTombstone(); + .assertTombstone(); } @Test public void test119Cleanup() throws Exception { - final String TEST_NAME = "test119Cleanup"; - Task task = getTestTask(); OperationResult result = task.getResult(); repositoryService.deleteObject(ShadowType.class, ACCOUNT_BAD_OID, result); repositoryService.deleteObject(ShadowType.class, ACCOUNT_JBOND_OID, result); - assertShadows(0 + getNumberOfBaseContextShadows()); + assertShadows(getNumberOfBaseContextShadows()); } @Test public void test120AddAccountWill() throws Exception { - final String TEST_NAME = "test120AddAccountWill"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -837,7 +807,7 @@ public void test120AddAccountWill() throws Exception { assertEquals(ACCOUNT_WILL_OID, addedObjectOid); - ShadowType repoShadowTypeAfter = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); + ShadowType repoShadowTypeAfter = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal (repo)", "uid=will,ou=People,dc=example,dc=com", repoShadowTypeAfter.getName()); assertAttribute(repoShadowTypeAfter, getSecondaryIdentifierQName(), StringUtils.lowerCase(ACCOUNT_WILL_DN)); @@ -849,9 +819,7 @@ public void test120AddAccountWill() throws Exception { } @Test - public void test121RenameAccountWillOnResource() throws Exception{ - String TEST_NAME = "test121RenameAccountWillOnResource"; - + public void test121RenameAccountWillOnResource() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -860,7 +828,7 @@ public void test121RenameAccountWillOnResource() throws Exception{ Entry entry = openDJController.fetchEntry("uid=will123,ou=People,dc=example,dc=com"); assertNotNull("Entry with dn uid=will123,ou=People,dc=example,dc=com does not exist", entry); - ShadowType repoShadowType = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); + ShadowType repoShadowType = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal (repo)", "uid=will,ou=People,dc=example,dc=com", repoShadowType.getName()); assertAttribute(repoShadowType, getSecondaryIdentifierQName(), StringUtils.lowerCase(ACCOUNT_WILL_DN)); @@ -869,7 +837,7 @@ public void test121RenameAccountWillOnResource() throws Exception{ PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=will123,ou=People,dc=example,dc=com", provisioningAccountType.getName()); assertAttribute(provisioningAccountType, getSecondaryIdentifierQName(), "uid=will123,ou=People,dc=example,dc=com"); - repoShadowType = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); + repoShadowType = getShadowRepo(ACCOUNT_WILL_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal (repo after provisioning)", "uid=will123,ou=People,dc=example,dc=com", repoShadowType.getName()); assertAttribute(repoShadowType, getSecondaryIdentifierQName(), "uid=will123,ou=people,dc=example,dc=com"); @@ -878,30 +846,21 @@ public void test121RenameAccountWillOnResource() throws Exception{ @Test public void test125AddObjectNull() throws Exception { - final String TEST_NAME = "test125AddObjectNull"; - Task task = getTestTask(); OperationResult result = task.getResult(); - String addedObjectOid = null; - try { - - // WHEN - addedObjectOid = provisioningService.addObject(null, null, null, task, result); + String addedObjectOid = provisioningService.addObject(null, null, null, task, result); Assert.fail("Expected IllegalArgumentException but haven't got one."); - } catch(IllegalArgumentException ex){ + assertShadows(1 + getNumberOfBaseContextShadows()); + } catch (IllegalArgumentException ex) { assertEquals("Object to add must not be null.", ex.getMessage()); } - - assertShadows(1 + getNumberOfBaseContextShadows()); } @Test public void test130AddDeleteAccountSparrow() throws Exception { - final String TEST_NAME = "test130AddDeleteAccountSparrow"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -922,8 +881,7 @@ public void test130AddDeleteAccountSparrow() throws Exception { ShadowType objType = null; try { - provisioningService.getObject(ShadowType.class, ACCOUNT_SPARROW_OID, - null, task, result); + provisioningService.getObject(ShadowType.class, ACCOUNT_SPARROW_OID, null, task, result); Assert.fail("Expected exception ObjectNotFoundException, but haven't got one."); } catch (ObjectNotFoundException ex) { display("Expected exception", ex); @@ -944,8 +902,6 @@ public void test130AddDeleteAccountSparrow() throws Exception { @Test public void test140AddAndModifyAccountJack() throws Exception { - final String TEST_NAME = "test140AddAndModifyAccountJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -966,9 +922,9 @@ public void test140AddAndModifyAccountJack() throws Exception { .asPrismObject().getDefinition().findPropertyDefinition(icfNamePath); ItemDelta renameDelta = prismContext.deltaFactory().property() .createModificationReplaceProperty(icfNamePath, icfNameDef, "uid=rename,ou=People,dc=example,dc=com"); - ((Collection)delta.getModifications()).add(renameDelta); + ((Collection) delta.getModifications()).add(renameDelta); - display("Object change",delta); + display("Object change", delta); // WHEN when(); @@ -983,7 +939,7 @@ public void test140AddAndModifyAccountJack() throws Exception { ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - display("Object after change",accountType); + display("Object after change", accountType); String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); List snValues = ShadowUtil.getAttributeValues(accountType, new QName(RESOURCE_NS, "sn")); @@ -1015,8 +971,6 @@ public void test140AddAndModifyAccountJack() throws Exception { @Test public void test145ModifyAccountJackJpegPhoto() throws Exception { - final String TEST_NAME = "test145ModifyAccountJackJpegPhoto"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1030,7 +984,7 @@ public void test145ModifyAccountJackJpegPhoto() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(jpegPhotoDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -1051,7 +1005,7 @@ public void test145ModifyAccountJackJpegPhoto() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty jpegPhotoAttr = attributesContainer.findProperty(jpegPhotoQName); @@ -1071,8 +1025,6 @@ public void test145ModifyAccountJackJpegPhoto() throws Exception { */ @Test public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { - final String TEST_NAME = "test147ModifyAccountJackGivenNameDuplicit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1090,7 +1042,7 @@ public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(givenNameDelta, titleDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -1110,7 +1062,7 @@ public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismAsserts.assertPropertyValue(attributesContainer, new ItemName(RESOURCE_OPENDJ_NS, "givenName"), "Jack"); @@ -1119,11 +1071,8 @@ public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { assertShadows(3); } - @Test public void test150ChangePassword() throws Exception { - final String TEST_NAME = "test150ChangePassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1136,22 +1085,21 @@ public void test150ChangePassword() throws Exception { ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_MODIFY_PASSWORD_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - display("Object before password change",accountType); + display("Object before password change", accountType); - String uid = null; - uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); + String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); Entry entryBefore = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account before", entryBefore); String passwordBefore = OpenDJController.getAttributeValue(entryBefore, "userPassword"); - assertNull("Unexpected password before change",passwordBefore); + assertNull("Unexpected password before change", passwordBefore); ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, "account-change-password.xml"), ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, accountType.asPrismObject().getDefinition()); - display("Object change",delta); + display("Object change", delta); // WHEN when(); @@ -1165,9 +1113,9 @@ public void test150ChangePassword() throws Exception { display("LDAP account after", entryAfter); String passwordAfter = OpenDJController.getAttributeValue(entryAfter, "userPassword"); - assertNotNull("The password was not changed",passwordAfter); + assertNotNull("The password was not changed", passwordAfter); - System.out.println("Changed password: "+passwordAfter); + System.out.println("Changed password: " + passwordAfter); openDJController.assertPassword(entryAfter.getDN().toString(), "mehAbigH4X0R"); @@ -1176,8 +1124,6 @@ public void test150ChangePassword() throws Exception { @Test public void test151AddObjectWithPassword() throws Exception { - final String TEST_NAME = "test151AddObjectWithPassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1189,19 +1135,19 @@ public void test151AddObjectWithPassword() throws Exception { String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); assertEquals(ACCOUNT_NEW_WITH_PASSWORD_OID, addedObjectOid); - ShadowType accountType = getShadowRepo( ACCOUNT_NEW_WITH_PASSWORD_OID).asObjectable(); + ShadowType accountType = getShadowRepo(ACCOUNT_NEW_WITH_PASSWORD_OID).asObjectable(); // assertEquals("lechuck", accountType.getName()); PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=lechuck,ou=People,dc=example,dc=com", accountType.getName()); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_NEW_WITH_PASSWORD_OID, - null,taskManager.createTaskInstance(), result).asObjectable(); + null, taskManager.createTaskInstance(), result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=lechuck,ou=People,dc=example,dc=com", provisioningAccountType.getName()); // assertEquals("lechuck", provisioningAccountType.getName()); String uid = null; for (Object e : accountType.getAttributes().getAny()) { if (getPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(e))) { - uid = ((Element)e).getTextContent(); + uid = ((Element) e).getTextContent(); } } assertNotNull(uid); @@ -1212,9 +1158,9 @@ public void test151AddObjectWithPassword() throws Exception { display("LDAP account after", entryAfter); String passwordAfter = OpenDJController.getAttributeValue(entryAfter, "userPassword"); - assertNotNull("The password was not changed",passwordAfter); + assertNotNull("The password was not changed", passwordAfter); - System.out.println("Account password: "+passwordAfter); + System.out.println("Account password: " + passwordAfter); openDJController.assertPassword(entryAfter.getDN().toString(), "t4k30v3rTh3W0rld"); @@ -1223,8 +1169,6 @@ public void test151AddObjectWithPassword() throws Exception { @Test public void test160SearchAccountsIterative() throws Exception { - final String TEST_NAME = "test160SearchAccountsIterative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1252,9 +1196,9 @@ public boolean handle(PrismObject prismObject, OperationResult paren assertEquals(new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME), shadow.getObjectClass()); assertEquals(RESOURCE_OPENDJ_OID, shadow.getResourceRef().getOid()); String idPrimaryVal = getAttributeValue(shadow, getPrimaryIdentifierQName()); - assertNotNull("No primary identifier ("+getPrimaryIdentifierQName().getLocalPart()+")", idPrimaryVal); + assertNotNull("No primary identifier (" + getPrimaryIdentifierQName().getLocalPart() + ")", idPrimaryVal); String idSecondaryVal = getAttributeValue(shadow, getSecondaryIdentifierQName()); - assertNotNull("No secondary ("+getSecondaryIdentifierQName().getLocalPart()+")", idSecondaryVal); + assertNotNull("No secondary (" + getSecondaryIdentifierQName().getLocalPart() + ")", idSecondaryVal); assertEquals("Wrong shadow name", idSecondaryVal.toLowerCase(), shadow.getName().getOrig().toLowerCase()); assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(resourceNamespace, "uid"))); assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(resourceNamespace, "cn"))); @@ -1287,8 +1231,6 @@ public boolean handle(PrismObject prismObject, OperationResult paren @Test public void test161SearchAccountsIterativeOffset2Page3() throws Exception { - final String TEST_NAME = "test161SearchAccountsIterativeOffset2Page3"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1334,8 +1276,6 @@ public boolean handle(PrismObject prismObject, OperationResult paren @Test public void test162SearchAccountsIterativeOffsetNullPage5() throws Exception { - final String TEST_NAME = "test162SearchAccountsIterativeOffsetNullPage5"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1393,9 +1333,7 @@ protected void assertShadows(int expectedCount) throws SchemaException { } @Test - public void test170DisableAccount() throws Exception{ - final String TEST_NAME = "test170DisableAccount"; - + public void test170DisableAccount() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1410,7 +1348,7 @@ public void test170DisableAccount() throws Exception{ ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue( REQUEST_DISABLE_ACCOUNT_SIMULATED_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, object.asPrismObject().getDefinition()); - display("Object change",delta); + display("Object change", delta); // WHEN when(); @@ -1422,7 +1360,7 @@ public void test170DisableAccount() throws Exception{ ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_DISABLE_SIMULATED_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - display("Object after change",accountType); + display("Object after change", accountType); assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, accountType.getActivation().getAdministrativeStatus()); @@ -1435,7 +1373,7 @@ public void test170DisableAccount() throws Exception{ display("LDAP account", response); String disabled = openDJController.getAttributeValue(response, "ds-pwp-account-disabled"); - assertNotNull("no ds-pwp-account-disabled attribute in account "+uid, disabled); + assertNotNull("no ds-pwp-account-disabled attribute in account " + uid, disabled); display("ds-pwp-account-disabled after change: " + disabled); @@ -1452,8 +1390,6 @@ public void test170DisableAccount() throws Exception{ @Test public void test175AddDisabledAccount() throws Exception { - final String TEST_NAME = "test175AddDisabledAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1467,7 +1403,7 @@ public void test175AddDisabledAccount() throws Exception { // THEN assertEquals(ACCOUNT_NEW_DISABLED_OID, addedObjectOid); - ShadowType accountType = getShadowRepo(ACCOUNT_NEW_DISABLED_OID).asObjectable(); + ShadowType accountType = getShadowRepo(ACCOUNT_NEW_DISABLED_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", "uid=rapp,ou=People,dc=example,dc=com", accountType.getName()); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_NEW_DISABLED_OID, @@ -1483,7 +1419,7 @@ public void test175AddDisabledAccount() throws Exception { display("LDAP account", response); String disabled = openDJController.getAttributeValue(response, "ds-pwp-account-disabled"); - assertNotNull("no ds-pwp-account-disabled attribute in account "+uid, disabled); + assertNotNull("no ds-pwp-account-disabled attribute in account " + uid, disabled); System.out.println("ds-pwp-account-disabled after change: " + disabled); @@ -1502,8 +1438,6 @@ public void test175AddDisabledAccount() throws Exception { */ @Test public void test176AddEnabledAccount() throws Exception { - final String TEST_NAME = "test176AddEnabledAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1517,7 +1451,7 @@ public void test176AddEnabledAccount() throws Exception { // THEN assertEquals(ACCOUNT_NEW_ENABLED_OID, addedObjectOid); - ShadowType accountType = getShadowRepo(ACCOUNT_NEW_ENABLED_OID).asObjectable(); + ShadowType accountType = getShadowRepo(ACCOUNT_NEW_ENABLED_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", "uid=cook,ou=People,dc=example,dc=com", accountType.getName()); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_NEW_ENABLED_OID, @@ -1538,8 +1472,6 @@ public void test176AddEnabledAccount() throws Exception { @Test public void test180GetUnlockedAccount() throws Exception { - final String TEST_NAME = "test180GetUnlockedAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1557,17 +1489,15 @@ public void test180GetUnlockedAccount() throws Exception { @Test public void test182GetLockedAccount() throws Exception { - final String TEST_NAME = "test182GetLockedAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); openDJController.executeLdifChange( "dn: uid=will123,ou=People,dc=example,dc=com\n" + - "changetype: modify\n" + - "replace: pager\n" + - "pager: 1" - ); + "changetype: modify\n" + + "replace: pager\n" + + "pager: 1" + ); // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, @@ -1582,9 +1512,7 @@ public void test182GetLockedAccount() throws Exception { } @Test - public void test184UnlockAccount() throws Exception{ - final String TEST_NAME = "test184UnlockAccount"; - + public void test184UnlockAccount() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1602,7 +1530,7 @@ public void test184UnlockAccount() throws Exception{ PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); String uid = ShadowUtil.getSingleStringAttributeValue(shadow.asObjectable(), getPrimaryIdentifierQName()); assertNotNull(uid); @@ -1613,17 +1541,14 @@ public void test184UnlockAccount() throws Exception{ display("LDAP account", response); String pager = openDJController.getAttributeValue(response, "pager"); - assertNull("Pager attribute found in account "+uid+": "+pager, pager); + assertNull("Pager attribute found in account " + uid + ": " + pager, pager); PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); } - @Test public void test200SearchObjectsIterative() throws Exception { - final String TEST_NAME = "test200SearchObjectsIterative"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1664,8 +1589,6 @@ public boolean handle(PrismObject object, OperationResult parentResu @Test public void test201SearchObjects() throws Exception { - final String TEST_NAME = "test201SearchObjects"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1699,9 +1622,7 @@ public void test201SearchObjects() throws Exception { } @Test - public void test202SearchObjectsCompexFilter() throws Exception { - final String TEST_NAME = "test202SearchObjectsCompexFilter"; - + public void test202SearchObjectsComplexFilter() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1715,7 +1636,7 @@ public void test202SearchObjectsCompexFilter() throws Exception { // WHEN when(); List> objListType = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1735,8 +1656,6 @@ public void test202SearchObjectsCompexFilter() throws Exception { @Test public void test203SearchObjectsByDnExists() throws Exception { - final String TEST_NAME = "test203SearchObjectsByDnExists"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1748,7 +1667,7 @@ public void test203SearchObjectsByDnExists() throws Exception { // WHEN when(); List> objListType = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1775,8 +1694,6 @@ public void test203SearchObjectsByDnExists() throws Exception { */ @Test public void test205SearchObjectsByDnNotExists() throws Exception { - final String TEST_NAME = "test205SearchObjectsByDnNotExists"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1789,7 +1706,7 @@ public void test205SearchObjectsByDnNotExists() throws Exception { // WHEN when(); List> objListType = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1810,9 +1727,7 @@ public void test205SearchObjectsByDnNotExists() throws Exception { * MID-5383 */ @Test - public void test206SearchObjectsCompexFilterStartsWith() throws Exception { - final String TEST_NAME = "test206SearchObjectsCompexFilterStartsWith"; - + public void test206SearchObjectsComplexFilterStartsWith() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1826,7 +1741,7 @@ public void test206SearchObjectsCompexFilterStartsWith() throws Exception { // WHEN when(); List> objListType = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1843,11 +1758,8 @@ public void test206SearchObjectsCompexFilterStartsWith() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - @Test public void test230SearchObjectsPagedNoOffset() throws Exception { - final String TEST_NAME = "test230SearchObjectsPagedNoOffset"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1863,14 +1775,14 @@ public void test230SearchObjectsPagedNoOffset() throws Exception { // WHEN when(); SearchResultList> searchResults = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); assertSuccess(result); display("Search resutls", searchResults); - assertSearchResults(searchResults, "cook", "drake", "hbarbossa" ); + assertSearchResults(searchResults, "cook", "drake", "hbarbossa"); assertConnectorOperationIncrement(1, 7); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); @@ -1881,8 +1793,6 @@ public void test230SearchObjectsPagedNoOffset() throws Exception { @Test public void test231SearchObjectsPagedOffsetZero() throws Exception { - final String TEST_NAME = "test231SearchObjectsPagedOffsetZero"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1898,7 +1808,7 @@ public void test231SearchObjectsPagedOffsetZero() throws Exception { // WHEN when(); SearchResultList> searchResults = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1916,8 +1826,6 @@ public void test231SearchObjectsPagedOffsetZero() throws Exception { @Test public void test232SearchObjectsPagedOffset() throws Exception { - final String TEST_NAME = "test232SearchObjectsPagedOffset"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1941,7 +1849,7 @@ public void test232SearchObjectsPagedOffset() throws Exception { display("Search resutls", searchResults); // The results should be this: - assertSearchResults(searchResults, "hbarbossa", "idm", "jbeckett", "jbond", "jgibbs" ); + assertSearchResults(searchResults, "hbarbossa", "idm", "jbeckett", "jbond", "jgibbs"); assertConnectorOperationIncrement(1, 11); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); @@ -1952,8 +1860,6 @@ public void test232SearchObjectsPagedOffset() throws Exception { @Test public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { - final String TEST_NAME = "test233SearchObjectsPagedNoOffsetSortSn"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1971,7 +1877,7 @@ public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { // WHEN when(); SearchResultList> searchResults = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -1979,7 +1885,7 @@ public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { assertSuccess(result); display("Search resutls", searchResults); - assertSearchResults(searchResults, "monk", "hbarbossa", "jbeckett", "jbond" ); + assertSearchResults(searchResults, "monk", "hbarbossa", "jbeckett", "jbond"); assertConnectorOperationIncrement(1, 9); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); @@ -1990,8 +1896,6 @@ public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { @Test public void test234SearchObjectsPagedOffsetSortSn() throws Exception { - final String TEST_NAME = "test234SearchObjectsPagedOffsetSortSn"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2009,7 +1913,7 @@ public void test234SearchObjectsPagedOffsetSortSn() throws Exception { // WHEN when(); List> searchResults = - provisioningService.searchObjects(ShadowType.class, query, null, task, result); + provisioningService.searchObjects(ShadowType.class, query, null, task, result); // THEN then(); @@ -2017,7 +1921,7 @@ public void test234SearchObjectsPagedOffsetSortSn() throws Exception { assertSuccess(result); display("Search resutls", searchResults); - assertSearchResults(searchResults, "jbeckett", "jbond", "cook", "drake" ); + assertSearchResults(searchResults, "jbeckett", "jbond", "cook", "drake"); assertConnectorOperationIncrement(1, 9); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); @@ -2026,12 +1930,12 @@ public void test234SearchObjectsPagedOffsetSortSn() throws Exception { private void assertSearchResults(List> searchResults, String... expectedUids) { assertEquals("Unexpected number of search results", expectedUids.length, searchResults.size()); int i = 0; - for (PrismObject searchResult: searchResults) { + for (PrismObject searchResult : searchResults) { assertShadowSanity(searchResult); ResourceAttribute uidAttr = ShadowUtil.getAttribute(searchResult, new QName(RESOURCE_NS, "uid")); String uid = uidAttr.getRealValues().iterator().next(); display("found uid", uid); - assertEquals("Wrong uid (index "+i+")", expectedUids[i], uid); + assertEquals("Wrong uid (index " + i + ")", expectedUids[i], uid); i++; } } @@ -2042,8 +1946,6 @@ private void assertSearchResults(List> searchResults, St */ @Test public void test250CountAccounts() throws Exception { - final String TEST_NAME = "test250CountAccounts"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2059,7 +1961,7 @@ public void test250CountAccounts() throws Exception { assertSuccess(result); display("All accounts count", count); - assertEquals("Unexpected number of search results", (Integer)14, count); + assertEquals("Unexpected number of search results", (Integer) 14, count); } /** @@ -2068,8 +1970,6 @@ public void test250CountAccounts() throws Exception { */ @Test public void test252CountLdapGroups() throws Exception { - final String TEST_NAME = "test252CountLdapGroups"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2092,14 +1992,11 @@ protected Integer getExpectedLdapGroupCountTest25x() { return 1; } - /** * The exception comes from the resource. There is no shadow for this object. */ @Test public void test300AddObjectObjectAlreadyExistResource() throws Exception { - final String TEST_NAME = "test300AddObjectObjectAlreadyExistResource"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2126,8 +2023,6 @@ public void test300AddObjectObjectAlreadyExistResource() throws Exception { @Test public void test310AddObjectNoSn() throws Exception { - final String TEST_NAME = "test310AddObjectNoSn"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2157,8 +2052,6 @@ public void test310AddObjectNoSn() throws Exception { @Test public void test320AddAccountPosix() throws Exception { - final String TEST_NAME = "test320AddAccountPosix"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2173,7 +2066,7 @@ public void test320AddAccountPosix() throws Exception { then(); assertEquals(ACCOUNT_POSIX_MCMUTTON_OID, addedObjectOid); - ShadowType repoShadowType = getShadowRepo(ACCOUNT_POSIX_MCMUTTON_OID).asObjectable(); + ShadowType repoShadowType = getShadowRepo(ACCOUNT_POSIX_MCMUTTON_OID).asObjectable(); display("Repo shadow", repoShadowType); PrismAsserts.assertEqualsPolyString("Name not equal (repo)", ACCOUNT_POSIX_MCMUTTON_DN, repoShadowType.getName()); assertAttribute(repoShadowType, getSecondaryIdentifierQName(), StringUtils.lowerCase(ACCOUNT_POSIX_MCMUTTON_DN)); @@ -2207,15 +2100,13 @@ public void test320AddAccountPosix() throws Exception { @Test public void test322ModifyAccountPosix() throws Exception { - final String TEST_NAME = "test322ModifyAccountPosix"; - Task task = getTestTask(); OperationResult result = task.getResult(); ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_POSIX_MCMUTTON_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, getShadowDefinition()); - display("Object change",delta); + display("Object change", delta); // WHEN when(); @@ -2229,7 +2120,7 @@ public void test322ModifyAccountPosix() throws Exception { ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_POSIX_MCMUTTON_OID, null, task, result).asObjectable(); - display("Object after change",accountType); + display("Object after change", accountType); String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); @@ -2252,8 +2143,6 @@ public void test322ModifyAccountPosix() throws Exception { @Test public void test329DeleteAccountPosix() throws Exception { - final String TEST_NAME = "test329DeleteAccountPosix"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2289,8 +2178,6 @@ public void test329DeleteAccountPosix() throws Exception { */ @Test public void test330SearchForPosixAccount() throws Exception { - final String TEST_NAME = "test330SearchForPosixAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2308,7 +2195,7 @@ public void test330SearchForPosixAccount() throws Exception { // WHEN when(); List> objListType = - provisioningService.searchObjects(ShadowType.class, query, null, null, result); + provisioningService.searchObjects(ShadowType.class, query, null, null, result); // THEN then(); @@ -2332,12 +2219,8 @@ public void test330SearchForPosixAccount() throws Exception { // TODO: synchronization of auxiliary object classes - - @Test public void test400AddGroupSwashbucklers() throws Exception { - final String TEST_NAME = "test400AddGroupSwashbucklers"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2352,7 +2235,7 @@ public void test400AddGroupSwashbucklers() throws Exception { then(); assertEquals(GROUP_SWASHBUCKLERS_OID, addedObjectOid); - ShadowType shadowType = getShadowRepo(GROUP_SWASHBUCKLERS_OID).asObjectable(); + ShadowType shadowType = getShadowRepo(GROUP_SWASHBUCKLERS_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", GROUP_SWASHBUCKLERS_DN, shadowType.getName()); PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, GROUP_SWASHBUCKLERS_OID, @@ -2377,8 +2260,6 @@ public void test400AddGroupSwashbucklers() throws Exception { @Test public void test402AddAccountMorganWithAssociation() throws Exception { - final String TEST_NAME = "test402AddAccountMorganWithAssociation"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2399,15 +2280,15 @@ public void test402AddAccountMorganWithAssociation() throws Exception { ShadowAsserter provisioningShadowAsserter = assertShadowProvisioning(ACCOUNT_MORGAN_OID) .assertName(ACCOUNT_MORGAN_DN) .associations() - .assertSize(1) - .association(ASSOCIATION_GROUP_NAME) - .assertShadowOids(GROUP_SWASHBUCKLERS_OID) - .end() - .end(); + .assertSize(1) + .association(ASSOCIATION_GROUP_NAME) + .assertShadowOids(GROUP_SWASHBUCKLERS_OID) + .end() + .end(); String uid = provisioningShadowAsserter .attributes() - .getValue(getPrimaryIdentifierQName()); + .getValue(getPrimaryIdentifierQName()); assertNotNull(uid); // List associations = provisioningShadowType.getAssociation(); @@ -2417,13 +2298,13 @@ public void test402AddAccountMorganWithAssociation() throws Exception { Entry accountEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", accountEntry); - assertNotNull("No LDAP account entry"); + assertNotNull("No LDAP account entry", accountEntry); String accountDn = accountEntry.getDN().toString(); assertEquals("Wrong account DN", ACCOUNT_MORGAN_DN, accountDn); Entry groupEntry = openDJController.fetchEntry(GROUP_SWASHBUCKLERS_DN); display("LDAP group", groupEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", groupEntry); openDJController.assertUniqueMember(groupEntry, accountDn); assertShadows(19); @@ -2431,8 +2312,6 @@ public void test402AddAccountMorganWithAssociation() throws Exception { @Test public void test403modifyMorganReplaceAssociation() throws Exception { - final String TEST_NAME = "test403modifyMorganReplaceAssociation"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2456,10 +2335,10 @@ public void test403modifyMorganReplaceAssociation() throws Exception { ShadowAsserter provisioningShadowAsserter = assertShadowProvisioning(ACCOUNT_MORGAN_OID) .assertName(ACCOUNT_MORGAN_DN) .associations() - .assertSize(1) - .association(ASSOCIATION_GROUP_NAME) - .assertShadowOids(GROUP_SWASHBUCKLERS_OID) - .end() + .assertSize(1) + .association(ASSOCIATION_GROUP_NAME) + .assertShadowOids(GROUP_SWASHBUCKLERS_OID) + .end() .end(); String uid = provisioningShadowAsserter @@ -2469,23 +2348,20 @@ public void test403modifyMorganReplaceAssociation() throws Exception { Entry accountEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", accountEntry); - assertNotNull("No LDAP account entry"); + assertNotNull("No LDAP account entry", accountEntry); String accountDn = accountEntry.getDN().toString(); assertEquals("Wrong account DN", ACCOUNT_MORGAN_DN, accountDn); Entry groupEntry = openDJController.fetchEntry(GROUP_SWASHBUCKLERS_DN); display("LDAP group", groupEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", groupEntry); openDJController.assertUniqueMember(groupEntry, accountDn); assertShadows(19); } - @Test public void test405GetGroupSwashbucklers() throws Exception { - final String TEST_NAME = "test405GetGroupSwashbucklers"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2497,7 +2373,7 @@ public void test405GetGroupSwashbucklers() throws Exception { // THEN then(); ShadowType provisioningShadowType = provisioningShadow.asObjectable(); - assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), + assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(provisioningShadowType.getName().getOrig())); String uid = ShadowUtil.getSingleStringAttributeValue(provisioningShadowType, getPrimaryIdentifierQName()); @@ -2505,9 +2381,10 @@ public void test405GetGroupSwashbucklers() throws Exception { ResourceAttribute memberAttr = ShadowUtil.getAttribute(provisioningShadow, new QName(RESOURCE_OPENDJ_NS, GROUP_MEMBER_ATTR_NAME)); assertNull("Member attribute sneaked in", memberAttr); + // TODO entry? group? not account? seems like copy/paste error from cases above Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP group", ldapEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", ldapEntry); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong group DN", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(groupDn)); @@ -2516,15 +2393,13 @@ public void test405GetGroupSwashbucklers() throws Exception { @Test public void test410CreateLdapGroupAndSearchGroups() throws Exception { - final String TEST_NAME = "test410CreateLdapGroupAndSearchGroups"; - Task task = getTestTask(); OperationResult result = task.getResult(); openDJController.addEntry("dn: cn=seadogs,ou=groups,dc=EXAMPLE,dc=com\n" + - "objectClass: groupOfUniqueNames\n" + - "objectClass: top\n" + - "cn: seadogs"); + "objectClass: groupOfUniqueNames\n" + + "objectClass: top\n" + + "cn: seadogs"); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); @@ -2549,19 +2424,17 @@ public void test410CreateLdapGroupAndSearchGroups() throws Exception { @Test public void test412CreateLdapGroupWithMemberAndGet() throws Exception { - final String TEST_NAME = "test412CreateLdapGroupWithMemberAndGet"; - Task task = getTestTask(); OperationResult result = task.getResult(); openDJController.addEntry("dn: cn=sailor,ou=Groups,dc=example,dc=com\n" + - "objectClass: groupOfUniqueNames\n" + - "objectClass: top\n" + - "cn: sailor\n" + - "uniqueMember: uid=MOrgan,ou=PEOPLE,dc=example,dc=com"); + "objectClass: groupOfUniqueNames\n" + + "objectClass: top\n" + + "cn: sailor\n" + + "uniqueMember: uid=MOrgan,ou=PEOPLE,dc=example,dc=com"); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, - RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); + ObjectQueryUtil.createResourceAndObjectClassQuery( + RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); // WHEN when(); @@ -2583,11 +2456,8 @@ public void test412CreateLdapGroupWithMemberAndGet() throws Exception { assertShadows(21); } - @Test public void test414AddGroupCorsairsAssociateUser() throws Exception { - final String TEST_NAME = "test414AddGroupCorsairsAssociateUser"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2602,7 +2472,7 @@ public void test414AddGroupCorsairsAssociateUser() throws Exception { then(); assertEquals(GROUP_CORSAIRS_OID, addedObjectOid); - ShadowType shadowType = getShadowRepo(GROUP_CORSAIRS_OID).asObjectable(); + ShadowType shadowType = getShadowRepo(GROUP_CORSAIRS_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", GROUP_CORSAIRS_DN, shadowType.getName()); // Do NOT read provisioning shadow here. We want everything to be "fresh" @@ -2612,8 +2482,6 @@ public void test414AddGroupCorsairsAssociateUser() throws Exception { @Test public void test416AssociateUserToCorsairs() throws Exception { - final String TEST_NAME = "test416AssociateUserToCorsairs"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2632,7 +2500,7 @@ public void test416AssociateUserToCorsairs() throws Exception { Entry groupEntry = openDJController.fetchEntry(GROUP_CORSAIRS_DN); display("LDAP group", groupEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", groupEntry); openDJController.assertUniqueMember(groupEntry, ACCOUNT_MORGAN_DN); assertShadows(22); @@ -2640,8 +2508,6 @@ public void test416AssociateUserToCorsairs() throws Exception { @Test public void test418GetMorgan() throws Exception { - final String TEST_NAME = "test418GetMorgan"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2667,8 +2533,6 @@ public void test418GetMorgan() throws Exception { */ @Test public void test429DeleteAccountMorgan() throws Exception { - final String TEST_NAME = "test429DeleteAccountMorgan"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2698,7 +2562,7 @@ public void test429DeleteAccountMorgan() throws Exception { Entry groupEntry = openDJController.fetchEntry(GROUP_SWASHBUCKLERS_DN); display("LDAP group", groupEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", groupEntry); openDJController.assertNoUniqueMember(groupEntry, ACCOUNT_MORGAN_DN); assertShadows(21); @@ -2706,8 +2570,6 @@ public void test429DeleteAccountMorgan() throws Exception { @Test public void test450ListGroupsObjectclass() throws Exception { - final String TEST_NAME = "test450ListGroupsObjectclass"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2732,8 +2594,6 @@ public void test450ListGroupsObjectclass() throws Exception { @Test public void test452ListLdapGroupsKindIntent() throws Exception { - final String TEST_NAME = "test452ListLdapGroupsKindIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2758,8 +2618,6 @@ public void test452ListLdapGroupsKindIntent() throws Exception { @Test public void test454ListSpecialGroupsKindIntent() throws Exception { - final String TEST_NAME = "test454ListSpecialGroupsKindIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2786,8 +2644,6 @@ public void test454ListSpecialGroupsKindIntent() throws Exception { @Test public void test456AddGroupSpecialists() throws Exception { - final String TEST_NAME = "test456AddGroupSpecialists"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2802,7 +2658,7 @@ public void test456AddGroupSpecialists() throws Exception { then(); assertEquals(GROUP_SPECIALISTS_OID, addedObjectOid); - ShadowType shadowType = getShadowRepo(GROUP_SPECIALISTS_OID).asObjectable(); + ShadowType shadowType = getShadowRepo(GROUP_SPECIALISTS_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", GROUP_SPECIALISTS_DN, shadowType.getName()); PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, GROUP_SPECIALISTS_OID, @@ -2818,7 +2674,7 @@ public void test456AddGroupSpecialists() throws Exception { Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP group", ldapEntry); - assertNotNull("No LDAP group entry"); + assertNotNull("No LDAP group entry", ldapEntry); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong group DN", dnMatchingRule.normalize(GROUP_SPECIALISTS_DN), dnMatchingRule.normalize(groupDn)); @@ -2827,8 +2683,6 @@ public void test456AddGroupSpecialists() throws Exception { @Test public void test457ListLdapGroupsKindIntent() throws Exception { - final String TEST_NAME = "test457ListLdapGroupsKindIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2853,8 +2707,6 @@ public void test457ListLdapGroupsKindIntent() throws Exception { @Test public void test458ListSpecialGroupsKindIntent() throws Exception { - final String TEST_NAME = "test458ListSpecialGroupsKindIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2887,8 +2739,6 @@ public void test458ListSpecialGroupsKindIntent() throws Exception { */ @Test public void test460ListOrganizationalUnitPeopleKindIntent() throws Exception { - final String TEST_NAME = "test460ListOrganizationalUnitPeopleKindIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2918,8 +2768,6 @@ public void test460ListOrganizationalUnitPeopleKindIntent() throws Exception { */ @Test public void test470AddAccountPolyDescription() throws Exception { - final String TEST_NAME = "test470AddAccountPolyDescription"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2929,7 +2777,7 @@ public void test470AddAccountPolyDescription() throws Exception { // WHEN when(); - String addedObjectOid = provisioningService.addObject(accountBefore, null, null, task, result); + provisioningService.addObject(accountBefore, null, null, task, result); // THEN then(); @@ -2944,7 +2792,7 @@ public void test470AddAccountPolyDescription() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_POLY_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); @@ -2956,7 +2804,6 @@ public void test470AddAccountPolyDescription() throws Exception { assertShadows(25); } - /** * Description is a "language tag" attribute (PolyString). * Simple modification with just "orig". No languages yet. @@ -2964,8 +2811,6 @@ public void test470AddAccountPolyDescription() throws Exception { */ @Test public void test472ModifyAccountJackDescriptionOrig() throws Exception { - final String TEST_NAME = "test472ModifyAccountJackDescriptionOrig"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2978,7 +2823,7 @@ public void test472ModifyAccountJackDescriptionOrig() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(descriptionDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -2996,13 +2841,13 @@ public void test472ModifyAccountJackDescriptionOrig() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); assertPolyString(descAttr.getValues().get(0).getValue(), "description after (shadow from provisioning)") - .assertOrig(descriptionBefore.getOrig()) - .assertNoLangs(); + .assertOrig(descriptionBefore.getOrig()) + .assertNoLangs(); assertShadows(25); } @@ -3014,8 +2859,6 @@ public void test472ModifyAccountJackDescriptionOrig() throws Exception { */ @Test public void test474ModifyAccountJackDescriptionLangEnSk() throws Exception { - final String TEST_NAME = "test474ModifyAccountJackDescriptionLangEnSk"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3047,14 +2890,13 @@ public void test474ModifyAccountJackDescriptionLangEnSk() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); assertPolyString(descAttr.getValues().get(0).getValue(), "description after (shadow from provisioning)") - .assertOrig(descriptionBefore.getOrig()) - .assertLangs(JACK_FULL_NAME_LANG_EN_SK); - + .assertOrig(descriptionBefore.getOrig()) + .assertLangs(JACK_FULL_NAME_LANG_EN_SK); assertShadows(25); } @@ -3066,8 +2908,6 @@ public void test474ModifyAccountJackDescriptionLangEnSk() throws Exception { */ @Test public void test476ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { - final String TEST_NAME = "test476ModifyAccountJackDescriptionLangEnSkRuHr"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3081,7 +2921,7 @@ public void test476ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(descriptionDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -3099,14 +2939,13 @@ public void test476ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); assertPolyString(descAttr.getValues().get(0).getValue(), "description after (shadow from provisioning)") - .assertOrig(descriptionBefore.getOrig()) - .assertLangs(JACK_FULL_NAME_LANG_EN_SK_RU_HR); - + .assertOrig(descriptionBefore.getOrig()) + .assertLangs(JACK_FULL_NAME_LANG_EN_SK_RU_HR); assertShadows(25); } @@ -3118,8 +2957,6 @@ public void test476ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { */ @Test public void test478ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { - final String TEST_NAME = "test478ModifyAccountJackDescriptionLangEnSkRuHr"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3133,7 +2970,7 @@ public void test478ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(descriptionDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -3151,14 +2988,13 @@ public void test478ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); assertPolyString(descAttr.getValues().get(0).getValue(), "description after (shadow from provisioning)") - .assertOrig(descriptionBefore.getOrig()) - .assertLangs(JACK_FULL_NAME_LANG_CZ_HR); - + .assertOrig(descriptionBefore.getOrig()) + .assertLangs(JACK_FULL_NAME_LANG_CZ_HR); assertShadows(25); } @@ -3169,8 +3005,6 @@ public void test478ModifyAccountJackDescriptionLangEnSkRuHr() throws Exception { */ @Test public void test478bModifyAccountJackDeleteDescription() throws Exception { - final String TEST_NAME = "test478bModifyAccountJackDeleteDescription"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3222,8 +3056,6 @@ public void test478bModifyAccountJackDeleteDescription() throws Exception { */ @Test public void test479ModifyAccountJackDescriptionJack() throws Exception { - final String TEST_NAME = "test479ModifyAccountJackDescriptionJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3236,7 +3068,7 @@ public void test479ModifyAccountJackDescriptionJack() throws Exception { Collection modifications = MiscSchemaUtil.createCollection(descriptionDelta); - display("Modifications",modifications); + display("Modifications", modifications); // WHEN when(); @@ -3254,22 +3086,19 @@ public void test479ModifyAccountJackDescriptionJack() throws Exception { PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - display("Object after change",shadow); + display("Object after change", shadow); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty descAttr = attributesContainer.findProperty(ATTRIBUTE_DESCRIPTION_QNAME); assertPolyString(descAttr.getValues().get(0).getValue(), "description after (shadow from provisioning)") - .assertOrig(descriptionBefore.getOrig()) - .assertNoLangs(); - + .assertOrig(descriptionBefore.getOrig()) + .assertNoLangs(); assertShadows(25); } @Test public void test480AddOuSuper() throws Exception { - final String TEST_NAME = "test480AddOuSuper"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3284,7 +3113,7 @@ public void test480AddOuSuper() throws Exception { then(); assertEquals(OU_SUPER_OID, addedObjectOid); - ShadowType shadowType = getShadowRepo(OU_SUPER_OID).asObjectable(); + ShadowType shadowType = getShadowRepo(OU_SUPER_OID).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", OU_SUPER_DN, shadowType.getName()); PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, OU_SUPER_OID, @@ -3298,7 +3127,7 @@ public void test480AddOuSuper() throws Exception { Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP ou", ldapEntry); - assertNotNull("No LDAP ou entry"); + assertNotNull("No LDAP ou entry", ldapEntry); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong ou DN", dnMatchingRule.normalize(OU_SUPER_DN), dnMatchingRule.normalize(groupDn)); @@ -3310,13 +3139,11 @@ public void test480AddOuSuper() throws Exception { * ou=sub,ou=Super,dc=example,dc=com. LDAP server should normally refuse to delete the Super OU * because it is not empty. But we have configured use of "tree delete" control here. * Therefore the delete should work. - * + *

* MID-5935 */ @Test public void test489DeleteOuSuperWithSub() throws Exception { - final String TEST_NAME = "test489DeleteOuSuperWithSub"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3337,15 +3164,13 @@ public void test489DeleteOuSuperWithSub() throws Exception { } protected void createSubOrg() throws IOException, LDIFException { - openDJController.addEntry("dn: ou=sub,ou=Super,dc=example,dc=com\n"+ - "objectClass: organizationalUnit\n"+ + openDJController.addEntry("dn: ou=sub,ou=Super,dc=example,dc=com\n" + + "objectClass: organizationalUnit\n" + "ou: sub"); } @Test - public void test701ConfiguredCapabilityNoRead() throws Exception{ - final String TEST_NAME = "test701ConfiguredCapabilityNoRead"; - + public void test701ConfiguredCapabilityNoRead() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3357,14 +3182,12 @@ public void test701ConfiguredCapabilityNoRead() throws Exception{ AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (UnsupportedOperationException ex) { - // this is expected.. + // this is expected.. } } @Test - public void test702ConfiguredCapabilityNoCreate() throws Exception{ - final String TEST_NAME = "test702ConfiguredCapabilityNoCreate"; - + public void test702ConfiguredCapabilityNoCreate() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3376,15 +3199,13 @@ public void test702ConfiguredCapabilityNoCreate() throws Exception{ AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (UnsupportedOperationException ex) { - LOGGER.info("exception: {}", ex.getMessage(), ex); - // this is expected.. + logger.info("exception: {}", ex.getMessage(), ex); + // this is expected.. } } @Test - public void test703ConfiguredCapabilityNoDelete() throws Exception{ - final String TEST_NAME = "test703ConfiguredCapabilityNoDelete"; - + public void test703ConfiguredCapabilityNoDelete() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3395,33 +3216,34 @@ public void test703ConfiguredCapabilityNoDelete() throws Exception{ AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (UnsupportedOperationException ex) { - // this is expected.. + // this is expected.. } } @Test - public void test704ConfiguredCapabilityNoUpdate() throws Exception{ - final String TEST_NAME = "test704ConfiguredCapabilityNoUpdate"; - + public void test704ConfiguredCapabilityNoUpdate() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-update.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); try { - PropertyDelta delta = prismContext.deltaFactory().property().createModificationReplaceProperty(ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceType.getNamespace(), "sn")), prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class), "doesnotmatter"); + PropertyDelta delta = + prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceType.getNamespace(), "sn")), + prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class), + "doesnotmatter"); Collection modifications = MiscUtil.createCollection(delta); provisioningService.modifyObject(ShadowType.class, ACCOUNT_WILL_OID, modifications, null, null, task, result); AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (UnsupportedOperationException ex) { - // this is expected.. + // this is expected.. } } @Test public void test710AddResourceOpenDjBadCredentials() throws Exception { - final String TEST_NAME = "test710AddResourceOpenDjBadCredentials"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3442,15 +3264,12 @@ public void test710AddResourceOpenDjBadCredentials() throws Exception { @Test public void test713ConnectionBadCredentials() throws Exception { - final String TEST_NAME = "test713ConnectionBadCredentials"; - Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN - OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_CREDENTIALS_OID, task); + OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_CREDENTIALS_OID, task); - display("Test connection result (expected failure)",testResult); + display("Test connection result (expected failure)", testResult); TestUtil.assertFailure(testResult); OperationResult connectorResult = assertSingleConnectorTestResult(testResult); @@ -3463,7 +3282,6 @@ public void test713ConnectionBadCredentials() throws Exception { @Test public void test720AddResourceOpenDjBadBindDn() throws Exception { - final String TEST_NAME = "test720AddResourceOpenDjBadBindDn"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3484,15 +3302,12 @@ public void test720AddResourceOpenDjBadBindDn() throws Exception { @Test public void test723ConnectionBadBindDn() throws Exception { - final String TEST_NAME = "test723ConnectionBadBindDn"; - Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN - OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_BIND_DN_OID, task); + OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_BIND_DN_OID, task); - display("Test connection result (expected failure)",testResult); + display("Test connection result (expected failure)", testResult); TestUtil.assertFailure(testResult); OperationResult connectorResult = assertSingleConnectorTestResult(testResult); @@ -3506,7 +3321,7 @@ protected void assertEntitlementGroup(PrismObject account, String en ShadowAssociationType associationType = IntegrationTestTools.assertAssociation(account, ASSOCIATION_GROUP_NAME, entitlementOid); PrismContainerValue identifiersCVal = associationType.getIdentifiers().asPrismContainerValue(); PrismProperty dnProp = identifiersCVal.findProperty(getSecondaryIdentifierQName()); - assertNotNull("No DN identifier in group association in "+account+", got "+identifiersCVal, dnProp); + assertNotNull("No DN identifier in group association in " + account + ", got " + identifiersCVal, dnProp); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java index 031cf17f7bf..bc02478b538 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java @@ -16,8 +16,6 @@ import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismProperty; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; @@ -38,8 +36,6 @@ public class TestOpenDjIncompletePassword extends TestOpenDj { protected static final File RESOURCE_OPENDJ_INCOMPLETE_PASSWORD_FILE = new File(TEST_DIR, "resource-opendj-incomplete-password.xml"); - private static final Trace LOGGER = TraceManager.getTrace(TestOpenDjIncompletePassword.class); - @Override protected File getResourceOpenDjFile() { return RESOURCE_OPENDJ_INCOMPLETE_PASSWORD_FILE; @@ -47,8 +43,8 @@ protected File getResourceOpenDjFile() { @Override protected void assertPasswordCapability(PasswordCapabilityType capPassword) { - assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), - capPassword.isReadable() == Boolean.TRUE); + assertTrue("Wrong password capability readable flag: " + capPassword.isReadable(), + capPassword.isReadable()); } @Override @@ -62,10 +58,10 @@ protected void assertShadowPassword(ShadowType provisioningShadow) { return; } ProtectedStringType passwordValue = passwordType.getValue(); - assertNull("Unexpected password value in "+provisioningShadow+": "+passwordValue, passwordValue); + assertNull("Unexpected password value in " + provisioningShadow + ": " + passwordValue, passwordValue); PrismContainerValue passwordContainer = passwordType.asPrismContainerValue(); PrismProperty valueProp = passwordContainer.findProperty(PasswordType.F_VALUE); - assertTrue("Incomplete flag is NOT set for password value in "+provisioningShadow, valueProp.isIncomplete()); + assertTrue("Incomplete flag is NOT set for password value in " + provisioningShadow, valueProp.isIncomplete()); } } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java index 6fe75b0d8a7..7b13361579d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java @@ -6,20 +6,12 @@ */ package com.evolveum.midpoint.provisioning.impl.opendj; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; -import com.evolveum.midpoint.prism.PrismContext; - -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -27,19 +19,16 @@ import org.testng.annotations.Test; import org.w3c.dom.Element; +import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.api.GenericConnectorException; -import com.evolveum.midpoint.schema.DeltaConvertor; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.PointInTimeType; -import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; -import com.evolveum.midpoint.schema.ResultHandler; -import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.*; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; @@ -47,26 +36,12 @@ import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Test for provisioning service implementation. Using OpenDJ. But NOT STARTING IT. @@ -77,11 +52,6 @@ @DirtiesContext public class TestOpenDjNegative extends AbstractOpenDjTest { - private static final Trace LOGGER = TraceManager.getTrace(TestOpenDjNegative.class); - - @Autowired - TaskManager taskManager; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -92,25 +62,23 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @BeforeClass - public static void stoptLdap() throws Exception { + public void stopLdap() { // Make sure that OpenDJ is stopped. We want to see the blood .. err ... errors try { openDJController.stop(); } catch (Exception ex) { - LOGGER.trace("Exeception during stopping already stopped LDAP (probably harmless)", ex); + logger.trace("Exeception during stopping already stopped LDAP (probably harmless)", ex); } } @Test public void test003Connection() throws Exception { - final String TEST_NAME = "test003Connection"; - Task task = getTestTask(); OperationResult result = task.getResult(); ResourceType resourceTypeBefore = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result).asObjectable(); display("Resource before testResource (repository)", resourceTypeBefore); - assertNotNull("No connector ref",resourceTypeBefore.getConnectorRef()); - assertNotNull("No connector ref OID",resourceTypeBefore.getConnectorRef().getOid()); + assertNotNull("No connector ref", resourceTypeBefore.getConnectorRef()); + assertNotNull("No connector ref OID", resourceTypeBefore.getConnectorRef().getOid()); connector = repositoryService.getObject(ConnectorType.class, resourceTypeBefore.getConnectorRef().getOid(), null, result); ConnectorType connectorType = connector.asObjectable(); assertNotNull(connectorType); @@ -120,12 +88,12 @@ public void test003Connection() throws Exception { AssertJUnit.assertNull("Found schema element before test connection. Bad test setup?", resourceXsdSchemaElementBefore); // WHEN - OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); + OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); - display("Test connection result (expected failure)",operationResult); + display("Test connection result (expected failure)", operationResult); TestUtil.assertFailure(operationResult); - PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, result); + PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); display("Resource after testResource (repository)", resourceRepoAfter); ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after testResource (repository, XML)", PrismTestUtil.serializeObjectToString(resourceTypeRepoAfter.asPrismObject(), PrismContext.LANG_XML)); @@ -138,11 +106,11 @@ public void test003Connection() throws Exception { @Test public void test004ResourceAndConnectorCaching() throws Exception { - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); Task task = createPlainTask(); // WHEN // This should NOT throw an exception. It should just indicate the failure in results - resource = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, task, result); + resource = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); ResourceType resourceType = resource.asObjectable(); // THEN @@ -155,7 +123,7 @@ public void test004ResourceAndConnectorCaching() throws Exception { assertNull("Resource schema found", resourceSchema); // WHEN - PrismObject resourceAgain = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, task, result); + PrismObject resourceAgain = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); // THEN result.computeStatus(); @@ -164,8 +132,8 @@ public void test004ResourceAndConnectorCaching() throws Exception { TestUtil.assertFailure(resourceAgain.asObjectable().getFetchResult()); ResourceType resourceTypeAgain = resourceAgain.asObjectable(); - assertNotNull("No connector ref",resourceTypeAgain.getConnectorRef()); - assertNotNull("No connector ref OID",resourceTypeAgain.getConnectorRef().getOid()); + assertNotNull("No connector ref", resourceTypeAgain.getConnectorRef()); + assertNotNull("No connector ref OID", resourceTypeAgain.getConnectorRef().getOid()); PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); @@ -182,13 +150,11 @@ public void test004ResourceAndConnectorCaching() throws Exception { */ @Test public void test110GetObjectNoShadow() throws Exception { - final String TEST_NAME = "test110GetObjectNoShadow"; - - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { - ShadowType acct = provisioningService.getObject(ShadowType.class, NON_EXISTENT_OID, null, taskManager.createTaskInstance(), result).asObjectable(); + provisioningService.getObject(ShadowType.class, NON_EXISTENT_OID, + null, taskManager.createTaskInstance(), result).asObjectable(); AssertJUnit.fail("getObject succeeded unexpectedly"); } catch (ObjectNotFoundException e) { @@ -208,18 +174,15 @@ public void test110GetObjectNoShadow() throws Exception { */ @Test public void test111GetObjectShadow() throws Exception { - final String TEST_NAME = "test111GetObjectShadow"; - - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { - - ShadowType acct = provisioningService.getObject(ShadowType.class, ACCOUNT_JBOND_OID, null, taskManager.createTaskInstance(), result).asObjectable(); + provisioningService.getObject(ShadowType.class, ACCOUNT_JBOND_OID, + null, taskManager.createTaskInstance(), result).asObjectable(); AssertJUnit.fail("getObject succeeded unexpectedly"); // } catch (CommunicationException e) { - } catch (ConfigurationException e){ + } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } @@ -230,10 +193,8 @@ public void test111GetObjectShadow() throws Exception { @Test public void test120ListResourceObjects() throws Exception { - final String TEST_NAME = "test120ListResourceObjects"; // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { // WHEN @@ -251,24 +212,21 @@ public void test120ListResourceObjects() throws Exception { } @Test - public void test121SearchAccounts() throws SchemaException, ObjectNotFoundException, - CommunicationException, ConfigurationException, SecurityViolationException, Exception { - final String TEST_NAME = "test121SearchAccounts"; + public void test121SearchAccounts() throws Exception { // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); - final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); - QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); + QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - try { + try { - // WHEN - provisioningService.searchObjects(ShadowType.class, query, null, null, result); + // WHEN + provisioningService.searchObjects(ShadowType.class, query, null, null, result); - AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); @@ -277,35 +235,33 @@ public void test121SearchAccounts() throws SchemaException, ObjectNotFoundExcept result.computeStatus(); display(result); TestUtil.assertFailure(result); - } + } @Test public void test122SearchAccountsIterative() throws SchemaException, ObjectNotFoundException, - CommunicationException, ConfigurationException, SecurityViolationException, Exception { - final String TEST_NAME = "test122SearchAccountsIterative"; + CommunicationException, SecurityViolationException, ExpressionEvaluationException { // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); - final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); - QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); + QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject prismObject, OperationResult parentResult) { - AssertJUnit.fail("handler called unexpectedly"); - return false; - } - }; + ResultHandler handler = new ResultHandler() { + @Override + public boolean handle(PrismObject prismObject, OperationResult parentResult) { + AssertJUnit.fail("handler called unexpectedly"); + return false; + } + }; - try { + try { - // WHEN - provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); + // WHEN + provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); - AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); @@ -313,14 +269,12 @@ public boolean handle(PrismObject prismObject, OperationResult paren result.computeStatus(); TestUtil.assertFailure(result); - } + } @Test public void test130AddAccountWill() throws Exception { - final String TEST_NAME = "test130AddAccountWill"; // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); ShadowType object = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); @@ -340,13 +294,10 @@ public void test130AddAccountWill() throws Exception { TestUtil.assertFailure(result); } - @Test public void test140AddDeleteAccountSparrow() throws Exception { - final String TEST_NAME = "test140AddDeleteAccountSparrow"; // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { @@ -365,14 +316,12 @@ public void test140AddDeleteAccountSparrow() throws Exception { @Test public void test150ModifyObject() throws Exception { - final String TEST_NAME = "test150ModifyObject"; // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_JACK_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, ShadowType.class, PrismTestUtil.getPrismContext()); - display("Object change",delta); + display("Object change", delta); try { @@ -391,10 +340,8 @@ public void test150ModifyObject() throws Exception { @Test public void test190Synchronize() throws Exception { - final String TEST_NAME = "test190Synhronize"; // GIVEN - Task task = taskManager.createTaskInstance(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, @@ -414,7 +361,6 @@ public void test190Synchronize() throws Exception { TestUtil.assertFailure(result); } - // ========================================================================================================= // Now lets replace the resource with one that has schema and capabilities. And re-run some of the tests. // OpenDJ is still down so the results should be the same. But the code may take a different path if @@ -423,10 +369,7 @@ public void test190Synchronize() throws Exception { @Test public void test500ReplaceResource() throws Exception { - final String TEST_NAME = "test500ReplaceResource"; - - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); // Delete should work fine even though OpenDJ is down provisioningService.deleteObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, taskManager.createTaskInstance(), result); @@ -447,10 +390,7 @@ public void test500ReplaceResource() throws Exception { */ @Test public void test510GetObjectNoShadow() throws Exception { - final String TEST_NAME = "test510GetObjectNoShadow"; - - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { ShadowType acct = provisioningService.getObject(ShadowType.class, NON_EXISTENT_OID, null, taskManager.createTaskInstance(), result).asObjectable(); @@ -474,10 +414,7 @@ public void test510GetObjectNoShadow() throws Exception { */ @Test public void test511GetObjectShadow() throws Exception { - final String TEST_NAME = "test511GetObjectShadow"; - - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); PrismObject acct = provisioningService.getObject(ShadowType.class, ACCOUNT_JBOND_OID, null, taskManager.createTaskInstance(), result); @@ -485,12 +422,12 @@ public void test511GetObjectShadow() throws Exception { result.computeStatus(); display("getObject result", result); - assertEquals("Expected result partial error but was "+result.getStatus(), + assertEquals("Expected result partial error but was " + result.getStatus(), OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = acct.asObjectable().getFetchResult(); display("getObject fetchResult", fetchResult); - assertEquals("Expected fetchResult partial error but was "+result.getStatus(), + assertEquals("Expected fetchResult partial error but was " + result.getStatus(), OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); } @@ -501,10 +438,8 @@ public void test511GetObjectShadow() throws Exception { */ @Test public void test520ListResourceObjects() throws Exception { - final String TEST_NAME = "test520ListResourceObjects"; // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); try { // WHEN @@ -522,23 +457,21 @@ public void test520ListResourceObjects() throws Exception { @Test public void test521SearchAccounts() throws SchemaException, ObjectNotFoundException, - CommunicationException, ConfigurationException, SecurityViolationException, Exception { - final String TEST_NAME = "test521SearchAccounts"; + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); - final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); - QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); + QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - try { + try { - // WHEN - provisioningService.searchObjects(ShadowType.class, query, null, null, result); + // WHEN + provisioningService.searchObjects(ShadowType.class, query, null, null, result); - AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); @@ -546,46 +479,42 @@ public void test521SearchAccounts() throws SchemaException, ObjectNotFoundExcept result.computeStatus(); TestUtil.assertFailure(result); - } + } @Test - public void test522SearchAccountsIterative() throws SchemaException, ObjectNotFoundException, - CommunicationException, ConfigurationException, SecurityViolationException, Exception { - final String TEST_NAME = "test522SearchAccountsIterative"; + public void test522SearchAccountsIterative() throws Exception { // GIVEN - OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + OperationResult result = getTestOperationResult(); - final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); - QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); + QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject prismObject, OperationResult parentResult) { - AssertJUnit.fail("handler called unexpectedly"); - return false; - } - }; + ResultHandler handler = new ResultHandler() { + @Override + public boolean handle(PrismObject prismObject, OperationResult parentResult) { + AssertJUnit.fail("handler called unexpectedly"); + return false; + } + }; - try { + try { - // WHEN - provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); + // WHEN + provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); - AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } assertFailure(result); - } + } @Test public void test530AddAccountWill() throws Exception { - final String TEST_NAME = "test530AddAccountWill"; // GIVEN Task task = getTestTask(); @@ -606,14 +535,14 @@ public void test530AddAccountWill() throws Exception { PrismObject repoShadow = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); ShadowAsserter.forShadow(repoShadow, "repo") - .display() - .assertName(ACCOUNT_WILL_DN) - .pendingOperations() + .display() + .assertName(ACCOUNT_WILL_DN) + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .delta() - .assertAdd(); + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .delta() + .assertAdd(); try { provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); @@ -626,17 +555,16 @@ public void test530AddAccountWill() throws Exception { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); PrismObject provisioningAccountFuture = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, task, result); ShadowAsserter.forShadow(provisioningAccountFuture, "future") - .display() - .assertName(ACCOUNT_WILL_DN) - .assertIsExists() - .assertNotDead(); + .display() + .assertName(ACCOUNT_WILL_DN) + .assertIsExists() + .assertNotDead(); } @Test public void test540DeleteObject() throws Exception { - final String TEST_NAME = "test540DeleteObject"; // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -649,42 +577,40 @@ public void test540DeleteObject() throws Exception { PrismObject repoShadow = repositoryService.getObject(ShadowType.class, ACCOUNT_SPARROW_OID, null, result); ShadowAsserter.forShadow(repoShadow, "repo") - .display() - .pendingOperations() + .display() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .delta() - .assertDelete(); + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .delta() + .assertDelete(); PrismObject provisioningAccount = provisioningService.getObject(ShadowType.class, ACCOUNT_SPARROW_OID, null, task, result); ShadowAsserter.forShadow(provisioningAccount, "provisioning") - .display() - .pendingOperations() + .display() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .delta() - .assertDelete(); + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .delta() + .assertDelete(); } @Test public void test550ModifyObject() throws Exception { - final String TEST_NAME = "test150ModifyObject"; // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_JACK_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, ShadowType.class, PrismTestUtil.getPrismContext()); - display("Object change",delta); + display("Object change", delta); // WHEN provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, task, result); - // THEN result.computeStatus(); display("deleteObject result", result); @@ -692,31 +618,29 @@ public void test550ModifyObject() throws Exception { PrismObject repoShadow = repositoryService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, result); ShadowAsserter.forShadow(repoShadow, "repo") - .display() - .pendingOperations() + .display() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .delta() - .assertModify(); + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .delta() + .assertModify(); PrismObject provisioningAccount = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, task, result); ShadowAsserter.forShadow(provisioningAccount, "provisioning") - .display() - .pendingOperations() + .display() + .pendingOperations() .singleOperation() - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .delta() - .assertModify(); + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .delta() + .assertModify(); } @Test public void test590Synchronize() throws Exception { - final String TEST_NAME = "test590Synhronize"; // GIVEN - Task task = taskManager.createTaskInstance(TestOpenDjNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, @@ -736,5 +660,4 @@ public void test590Synchronize() throws Exception { assertFailure(result); } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java index 5768e2a8d90..5096c6a2556 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java @@ -102,7 +102,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010Sanity() throws Exception { - final OperationResult result = createOperationalResult(); + final OperationResult result = createOperationResult(); // WHEN PrismObject resource = provisioningService.getObject(ResourceType.class, resourceType.getOid(), null, taskManager.createTaskInstance(), result); @@ -126,7 +126,7 @@ public void test010Sanity() throws Exception { @Test public void test100SyncAddWill() throws Exception { - final OperationResult result = createOperationalResult(); + final OperationResult result = createOperationResult(); Task syncTask = taskManager.getTask(SYNC_TASK_OID, result); AssertJUnit.assertNotNull(syncTask); @@ -185,7 +185,7 @@ public void test100SyncAddWill() throws Exception { @Test public void test500SyncAddProtected() throws Exception { - final OperationResult result = createOperationalResult(); + final OperationResult result = createOperationResult(); Task syncTask = taskManager.getTask(SYNC_TASK_OID, result); AssertJUnit.assertNotNull(syncTask); diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java index e0eab1fe6d3..0718fa3317e 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java @@ -30,6 +30,7 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; @@ -104,4 +105,12 @@ protected void assertContainerDefinition(PrismContainer container, String con QName qName = new QName(SchemaConstantsGenerated.NS_COMMON, contName); PrismAsserts.assertDefinition(container.getDefinition(), qName, xsdType, minOccurs, maxOccurs); } + + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java index 2060849a0ad..8e373e22e30 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java index 5ddb1efa7da..850f23a3d15 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java @@ -6,10 +6,7 @@ */ package com.evolveum.midpoint.provisioning.ucf.impl.connid; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.ArrayList; import java.util.Collection; @@ -40,8 +37,6 @@ import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; @@ -55,19 +50,17 @@ @ContextConfiguration(locations = { "classpath:ctx-ucf-connid-test.xml" }) public class TestUcfDummyMulti extends AbstractUcfDummyTest { - private static final Trace LOGGER = TraceManager.getTrace(TestUcfDummyMulti.class); - @Test public void test000PrismContextSanity() { SchemaRegistry schemaRegistry = PrismTestUtil.getPrismContext().getSchemaRegistry(); PrismSchema schemaIcfc = schemaRegistry.findSchemaByNamespace(SchemaConstants.NS_ICF_CONFIGURATION); - assertNotNull("ICFC schema not found in the context ("+SchemaConstants.NS_ICF_CONFIGURATION+")", schemaIcfc); + assertNotNull("ICFC schema not found in the context (" + SchemaConstants.NS_ICF_CONFIGURATION + ")", schemaIcfc); PrismContainerDefinition configurationPropertiesDef = - schemaIcfc.findContainerDefinitionByElementName(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); - assertNotNull("icfc:configurationProperties not found in icfc schema ("+ - SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME+")", configurationPropertiesDef); + schemaIcfc.findContainerDefinitionByElementName(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); + assertNotNull("icfc:configurationProperties not found in icfc schema (" + + SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME + ")", configurationPropertiesDef); PrismSchema schemaIcfs = schemaRegistry.findSchemaByNamespace(SchemaConstants.NS_ICF_SCHEMA); - assertNotNull("ICFS schema not found in the context ("+SchemaConstants.NS_ICF_SCHEMA+")", schemaIcfs); + assertNotNull("ICFS schema not found in the context (" + SchemaConstants.NS_ICF_SCHEMA + ")", schemaIcfs); } @Test @@ -116,8 +109,8 @@ public void test100AddAccount() throws Exception { // THEN DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_JACK_USERNAME); - assertNotNull("Account "+ACCOUNT_JACK_USERNAME+" was not created", dummyAccount); - assertNotNull("Account "+ACCOUNT_JACK_USERNAME+" has no username", dummyAccount.getName()); + assertNotNull("Account " + ACCOUNT_JACK_USERNAME + " was not created", dummyAccount); + assertNotNull("Account " + ACCOUNT_JACK_USERNAME + " has no username", dummyAccount.getName()); } @@ -151,8 +144,8 @@ public boolean handle(PrismObject shadow) { ConnectorOperationalStatus opStat = cc.getOperationalStatus(); display("stats", opStat); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)1, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumIdle()); } @Test @@ -187,7 +180,7 @@ public void run() { cc.search(accountDefinition, null, handler, null, null, null, null, result); } catch (CommunicationException | GenericFrameworkException | SchemaException | SecurityViolationException | ObjectNotFoundException e) { - LOGGER.error("Error in the search: {}", e.getMessage(), e); + logger.error("Error in the search: {}", e.getMessage(), e); } } }); @@ -199,8 +192,8 @@ public void run() { ConnectorOperationalStatus opStat = cc.getOperationalStatus(); display("stats (blocked)", opStat); - assertEquals("Wrong pool active", (Integer)1, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumIdle()); assertEquals("Unexpected number of search results", 0, searchResults.size()); @@ -215,8 +208,8 @@ public void run() { opStat = cc.getOperationalStatus(); display("stats (final)", opStat); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)1, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumIdle()); PrismObject searchResult = searchResults.get(0); display("Search result", searchResult); @@ -226,7 +219,6 @@ public void run() { public void test210TwoBlockingSearches() throws Exception { // GIVEN - final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // Determine object class from the schema @@ -263,7 +255,7 @@ public void run() { cc.search(accountDefinition, null, handler1, null, null, null, null, result1); } catch (CommunicationException | GenericFrameworkException | SchemaException | SecurityViolationException | ObjectNotFoundException e) { - LOGGER.error("Error in the search: {}", e.getMessage(), e); + logger.error("Error in the search: {}", e.getMessage(), e); } } }); @@ -275,8 +267,8 @@ public void run() { ConnectorOperationalStatus opStat = cc.getOperationalStatus(); display("stats (blocked 1)", opStat); - assertEquals("Wrong pool active", (Integer)1, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumIdle()); assertEquals("Unexpected number of search results", 0, searchResults1.size()); @@ -288,7 +280,7 @@ public void run() { cc.search(accountDefinition, null, handler2, null, null, null, null, result2); } catch (CommunicationException | GenericFrameworkException | SchemaException | SecurityViolationException | ObjectNotFoundException e) { - LOGGER.error("Error in the search: {}", e.getMessage(), e); + logger.error("Error in the search: {}", e.getMessage(), e); } } }); @@ -300,8 +292,8 @@ public void run() { opStat = cc.getOperationalStatus(); display("stats (blocked 2)", opStat); - assertEquals("Wrong pool active", (Integer)2, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 2, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumIdle()); assertEquals("Unexpected number of search results", 0, searchResults1.size()); @@ -318,8 +310,8 @@ public void run() { opStat = cc.getOperationalStatus(); display("stats (final)", opStat); - assertEquals("Wrong pool active", (Integer)0, opStat.getPoolStatusNumActive()); - assertEquals("Wrong pool active", (Integer)2, opStat.getPoolStatusNumIdle()); + assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumActive()); + assertEquals("Wrong pool active", (Integer) 2, opStat.getPoolStatusNumIdle()); PrismObject searchResult1 = searchResults1.get(0); display("Search result 1", searchResult1); @@ -329,12 +321,11 @@ public void run() { } private void checkUcfShadow(PrismObject shadow, ObjectClassComplexTypeDefinition objectClassDefinition) { - assertNotNull("No objectClass in shadow "+shadow, shadow.asObjectable().getObjectClass()); - assertEquals("Wrong objectClass in shadow "+shadow, objectClassDefinition.getTypeName(), shadow.asObjectable().getObjectClass()); + assertNotNull("No objectClass in shadow " + shadow, shadow.asObjectable().getObjectClass()); + assertEquals("Wrong objectClass in shadow " + shadow, objectClassDefinition.getTypeName(), shadow.asObjectable().getObjectClass()); Collection> attributes = ShadowUtil.getAttributes(shadow); - assertNotNull("No attributes in shadow "+shadow, attributes); - assertFalse("Empty attributes in shadow "+shadow, attributes.isEmpty()); + assertNotNull("No attributes in shadow " + shadow, attributes); + assertFalse("Empty attributes in shadow " + shadow, attributes.isEmpty()); } - } diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java index 2dfa807d31a..e4af410ee96 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java @@ -9,7 +9,6 @@ import static org.testng.AssertJUnit.*; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; import java.io.File; import java.io.IOException; @@ -53,14 +52,11 @@ import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.ldap.OpenDJController; -import com.evolveum.midpoint.test.util.AbstractSpringTest; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PagedSearchCapabilityType; @@ -81,7 +77,7 @@ * a lesser evil for now (MID-392) */ @ContextConfiguration(locations = { "classpath:ctx-ucf-connid-test.xml" }) -public class TestUcfOpenDj extends AbstractSpringTest { +public class TestUcfOpenDj extends AbstractUcfDummyTest { private static final File RESOURCE_OPENDJ_FILE = new File(UcfTestUtil.TEST_DIR, "resource-opendj.xml"); private static final File RESOURCE_OPENDJ_BAD_FILE = new File(UcfTestUtil.TEST_DIR, "resource-opendj-bad.xml"); @@ -95,14 +91,9 @@ public class TestUcfOpenDj extends AbstractSpringTest { private PrismSchema connectorSchema; private ResourceSchema resourceSchema; - private static final Trace LOGGER = TraceManager.getTrace(TestUcfOpenDj.class); - - @Autowired - ConnectorFactory connectorFactoryIcfImpl; - @Autowired - Protector protector; - @Autowired - PrismContext prismContext; + @Autowired ConnectorFactory connectorFactoryIcfImpl; + @Autowired Protector protector; + @Autowired PrismContext prismContext; protected static OpenDJController openDJController = new OpenDJController(); @@ -113,19 +104,19 @@ public void setup() throws SchemaException, SAXException, IOException { } @BeforeClass - public static void startLdap() throws Exception { - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("START: OpenDjUcfTest"); - LOGGER.info("------------------------------------------------------------------------------"); + public void startLdap() throws Exception { + logger.info("------------------------------------------------------------------------------"); + logger.info("START: OpenDjUcfTest"); + logger.info("------------------------------------------------------------------------------"); openDJController.startCleanServer(); } @AfterClass - public static void stopLdap() { + public void stopLdap() { openDJController.stop(); - LOGGER.info("------------------------------------------------------------------------------"); - LOGGER.info("STOP: OpenDjUcfTest"); - LOGGER.info("------------------------------------------------------------------------------"); + logger.info("------------------------------------------------------------------------------"); + logger.info("STOP: OpenDjUcfTest"); + logger.info("------------------------------------------------------------------------------"); } @BeforeMethod @@ -273,7 +264,7 @@ public void test100AddDeleteObject() throws Exception { Collection> identifiers = addSampleResourceObject("john", "John", "Smith"); - String uid = null; + String uid; for (ResourceAttribute resourceAttribute : identifiers) { if (SchemaConstants.ICFS_UID.equals(resourceAttribute.getElementName())) { uid = resourceAttribute.getValue(String.class).getValue(); @@ -408,15 +399,6 @@ private PropertyModificationOperation createDeleteAttributeChange(String propert return attributeModification; } - private PropertyModificationOperation createActivationChange(ActivationStatusType status) { - PrismObjectDefinition shadowDefinition = getShadowDefinition(ShadowType.class); - PropertyDelta delta = prismContext.deltaFactory().property().createDelta( - ItemPath.create(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), - shadowDefinition); - delta.setRealValuesToReplace(status); - return new PropertyModificationOperation(delta); - } - /** * Simple call to connector test() method. */ @@ -671,9 +653,7 @@ public void test610ChangePassword() throws Exception { ItemDeltaType propMod = new ItemDeltaType(); //create modification path - Document doc = DOMUtil.getDocument(); ItemPathType path = prismContext.itemPathParser().asItemPathType("credentials/password/value"); -// PropertyPath propPath = new PropertyPath(new PropertyPath(ResourceObjectShadowType.F_CREDENTIALS), CredentialsType.F_PASSWORD); propMod.setPath(path); //set the replace value diff --git a/repo/repo-cache/src/test/java/com/evolveum/midpoint/repo/cache/TestRepositoryCache.java b/repo/repo-cache/src/test/java/com/evolveum/midpoint/repo/cache/TestRepositoryCache.java index dc161b91145..7f5404ff40f 100644 --- a/repo/repo-cache/src/test/java/com/evolveum/midpoint/repo/cache/TestRepositoryCache.java +++ b/repo/repo-cache/src/test/java/com/evolveum/midpoint/repo/cache/TestRepositoryCache.java @@ -8,7 +8,8 @@ import static org.testng.AssertJUnit.assertEquals; -import static com.evolveum.midpoint.prism.util.PrismTestUtil.*; +import static com.evolveum.midpoint.prism.util.PrismTestUtil.displayCollection; +import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; import java.io.IOException; import java.util.Collection; @@ -44,9 +45,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -/** - * - */ @SuppressWarnings("SameParameterValue") @ContextConfiguration(locations = { "classpath:ctx-repo-cache-test.xml" }) public class TestRepositoryCache extends AbstractSpringTest { @@ -107,18 +105,18 @@ private void testGetObject(Class objectClass, boolean String oid = repositoryCache.addObject(object, null, result); PrismObject object1 = repositoryCache.getObject(objectClass, oid, null, result); - display("1st object retrieved", object1); + PrismTestUtil.display("1st object retrieved", object1); assertEquals("Wrong object1", object, object1); object1.asObjectable().setDescription("garbage"); PrismObject object2 = repositoryCache.getObject(objectClass, oid, null, result); - display("2nd object retrieved", object2); + PrismTestUtil.display("2nd object retrieved", object2); assertEquals("Wrong object2", object, object2); object2.asObjectable().setDescription("total garbage"); PrismObject object3 = repositoryCache.getObject(objectClass, oid, null, result); assertEquals("Wrong object3", object, object3); - display("3rd object retrieved", object3); + PrismTestUtil.display("3rd object retrieved", object3); dumpStatistics(); assertAddOperations(1); diff --git a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java index 2a1bc6bf71d..4ded99677f2 100644 --- a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java +++ b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java @@ -58,7 +58,7 @@ public void test100PlainExecuteEcho() throws Exception { final String TEST_NAME = "test100PlainExecuteEcho"; if (!isOsUnix()) { - displaySkip(TEST_NAME); + displaySkip(); return; } @@ -82,7 +82,7 @@ public void test110RedirExecuteEcho() throws Exception { final String TEST_NAME = "test110RedirExecuteEcho"; if (!isOsUnix()) { - displaySkip(TEST_NAME); + displaySkip(); return; } diff --git a/repo/repo-sql-impl-test/pom.xml b/repo/repo-sql-impl-test/pom.xml index cfe1d19eac7..dc7531feed9 100644 --- a/repo/repo-sql-impl-test/pom.xml +++ b/repo/repo-sql-impl-test/pom.xml @@ -174,6 +174,11 @@ jaxb-api test + + javax.annotation + javax.annotation-api + test + org.springframework spring-aspects @@ -188,13 +193,6 @@ com.evolveum.midpoint.infra test-util - test - - - com.evolveum.midpoint.tools - test-ng - 4.1-SNAPSHOT - test diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AbstractPhotoTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AbstractPhotoTest.java index 762be95ec9d..f83ef022b51 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AbstractPhotoTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AbstractPhotoTest.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2020 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 + * + * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ @@ -33,13 +33,6 @@ public abstract class AbstractPhotoTest extends BaseSQLRepo static final File TEST_DIR = new File("src/test/resources/photo"); - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - protected abstract Class getObjectType(); void checkObject(String oid, File file, OperationResult result) throws SchemaException, IOException, diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java index c99397ee8d8..8037824b992 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java @@ -28,8 +28,6 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.hibernate.query.Query; @@ -54,8 +52,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class AddGetObjectTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(AddGetObjectTest.class); - @Test(enabled = false) public void perfTest() throws Exception { Statistics stats = getFactory().getStatistics(); @@ -68,7 +64,7 @@ public void perfTest() throws Exception { long time = System.currentTimeMillis(); for (int i = 0; i < elements.size(); i++) { if (i % 500 == 0) { - LOGGER.info("Previous cycle time {}. Next cycle: {}", new Object[]{ + logger.info("Previous cycle time {}. Next cycle: {}", new Object[]{ (System.currentTimeMillis() - time - previousCycle), i}); previousCycle = System.currentTimeMillis() - time; } @@ -76,7 +72,7 @@ public void perfTest() throws Exception { PrismObject object = (PrismObject) elements.get(i); repositoryService.addObject(object, null, new OperationResult("add performance test")); } - LOGGER.info("Time to add objects ({}): {}", + logger.info("Time to add objects ({}): {}", new Object[]{elements.size(), (System.currentTimeMillis() - time)}); stats.logSummary(); @@ -100,7 +96,7 @@ public void addSameName() throws Exception { public void addGetDSEESyncDoubleTest() throws Exception { final File OBJECTS_FILE = new File("./../../samples/dsee/odsee-localhost-advanced-sync.xml"); if (!OBJECTS_FILE.exists()) { - LOGGER.warn("skipping addGetDSEESyncDoubleTest, file {} not found.", + logger.warn("skipping addGetDSEESyncDoubleTest, file {} not found.", new Object[]{OBJECTS_FILE.getPath()}); return; } @@ -117,7 +113,6 @@ public void addGetDSEESyncDoubleTest() throws Exception { @Test public void simpleAddGetTest() throws Exception { - LOGGER.info("===[ simpleAddGetTest ]==="); final File OBJECTS_FILE = new File(FOLDER_BASIC, "objects.xml"); List> objects = addGetCompare(OBJECTS_FILE); @@ -142,10 +137,10 @@ private List> addGetCompare(File file) throws Exception { long time = System.currentTimeMillis(); for (int i = 0; i < elements.size(); i++) { PrismObject object = elements.get(i); - LOGGER.info("Adding object {}, type {}", i + 1, object.getCompileTimeClass().getSimpleName()); + logger.info("Adding object {}, type {}", i + 1, object.getCompileTimeClass().getSimpleName()); oids.add(repositoryService.addObject(object, null, result)); } - LOGGER.info("Time to add objects ({}): {}", elements.size(), System.currentTimeMillis() - time); + logger.info("Time to add objects ({}): {}", elements.size(), System.currentTimeMillis() - time); List> objectsRead = new ArrayList<>(); int count = 0; @@ -169,7 +164,7 @@ private List> addGetCompare(File file) throws Exception { } PrismObject newObject = repositoryService.getObject(clazz, oids.get(i), optionsBuilder.build(), result); - LOGGER.info("AFTER READ: {}\nOld\n{}\nnew\n{}", object, object.debugDump(3), newObject.debugDump(3)); + logger.info("AFTER READ: {}\nOld\n{}\nnew\n{}", object, object.debugDump(3), newObject.debugDump(3)); checkContainersSize(newObject, object); System.out.println("OLD: " + object.findProperty(ObjectType.F_NAME).getValue()); System.out.println("NEW: " + newObject.findProperty(ObjectType.F_NAME).getValue()); @@ -187,16 +182,16 @@ private List> addGetCompare(File file) throws Exception { continue; } } - LOGGER.error(">>> {} Found {} changes for {}\n{}", (i + 1), + logger.error(">>> {} Found {} changes for {}\n{}", (i + 1), delta.getModifications().size(), newObject.toString(), delta.debugDump(3)); ItemDelta id = (ItemDelta) delta.getModifications().iterator().next(); if (id.isReplace()) { - LOGGER.debug("{}", id.getValuesToReplace().iterator().next()); + logger.debug("{}", id.getValuesToReplace().iterator().next()); } - LOGGER.error("{}", prismContext.serializerFor(PrismContext.LANG_XML).serialize(newObject)); + logger.error("{}", prismContext.serializerFor(PrismContext.LANG_XML).serialize(newObject)); } } catch (Throwable ex) { - LOGGER.error("Exception occurred for {}", object, ex); + logger.error("Exception occurred for {}", object, ex); throw new RuntimeException("Exception during processing of "+object+": "+ex.getMessage(), ex); } } @@ -213,7 +208,7 @@ private Integer size(PrismContainerValue value) { } private void checkContainerValuesSize(QName parentName, PrismContainerValue newValue, PrismContainerValue oldValue) { - LOGGER.info("Checking: " + parentName); + logger.info("Checking: " + parentName); AssertJUnit.assertEquals("Count doesn't match for '" + parentName + "' id="+newValue.getId(), size(oldValue), size(newValue)); List checked = new ArrayList<>(); @@ -243,7 +238,7 @@ private void checkContainerValuesSize(QName parentName, PrismContainerValue n } private void checkContainersSize(PrismContainer newContainer, PrismContainer oldContainer) { - LOGGER.info("checkContainersSize {} new {} old {}", + logger.info("checkContainersSize {} new {} old {}", newContainer.getElementName(), newContainer.size(), oldContainer.size()); AssertJUnit.assertEquals(newContainer.size(), oldContainer.size()); @@ -274,7 +269,6 @@ private void checkContainersSize(PrismContainer newContainer, PrismContainer old @Test public void addUserWithAssignmentExtension() throws Exception { - LOGGER.info("===[ addUserWithAssignmentExtension ]==="); File file = new File(FOLDER_BASIC, "user-assignment-extension.xml"); List> elements = prismContext.parserFor(file).parseObjects(); @@ -292,7 +286,7 @@ public void addUserWithAssignmentExtension() throws Exception { ObjectDelta delta = fileUser.diff(repoUser); AssertJUnit.assertNotNull(delta); - LOGGER.info("delta\n{}", delta.debugDump(3)); + logger.info("delta\n{}", delta.debugDump(3)); assertTrue(delta.isEmpty()); } @@ -303,7 +297,6 @@ public void addUserWithAssignmentExtension() throws Exception { */ @Test public void addGetFullAccount() throws Exception { - LOGGER.info("===[ addGetFullAccount ]==="); PrismObject fileAccount = prismContext.parseObject(new File(FOLDER_BASIC, "account-full.xml")); // apply appropriate schema @@ -318,7 +311,7 @@ public void addGetFullAccount() throws Exception { ObjectDelta delta = fileAccount.diff(repoAccount); AssertJUnit.assertNotNull(delta); - LOGGER.info("delta\n{}", new Object[]{delta.debugDump(3)}); + logger.info("delta\n{}", new Object[]{delta.debugDump(3)}); if (!delta.isEmpty()) { fail("delta is not empty: " + delta.debugDump()); } @@ -333,12 +326,9 @@ public void addGetFullAccount() throws Exception { @Test public void testAddGetSystemConfigFile() throws Exception { - final String TEST_NAME = "testAddGetSystemConfigFile"; - LOGGER.info("===[ {} ]===", TEST_NAME); - PrismObject securityPolicy = prismContext.parseObject(new File(FOLDER_BASIC, "security-policy-special.xml")); - OperationResult result = createResult(); + OperationResult result = createOperationResult(); String securityPolicyOid = "ce74cb86-c8e8-11e9-bee8-b37bf7a7ab4a"; String oid = repositoryService.addObject(securityPolicy, null, result); AssertJUnit.assertNotNull(oid); @@ -348,13 +338,13 @@ public void testAddGetSystemConfigFile() throws Exception { String systemCongigOid = "00000000-0000-0000-0000-000000000001"; PrismObject fileSystemConfig = prismContext.parseObject(new File(FOLDER_BASIC, "systemConfiguration.xml")); - LOGGER.info("System config from file: {}", fileSystemConfig.debugDump()); + logger.info("System config from file: {}", fileSystemConfig.debugDump()); oid = repositoryService.addObject(fileSystemConfig, null, result); AssertJUnit.assertNotNull(oid); AssertJUnit.assertEquals(systemCongigOid, oid); PrismObject repoSystemConfig = repositoryService.getObject(SystemConfigurationType.class, systemCongigOid, null, result); - LOGGER.info("System config from repo: {}", repoSystemConfig.debugDump()); + logger.info("System config from repo: {}", repoSystemConfig.debugDump()); AssertJUnit.assertNull("global security policy not null", repoSystemConfig.asObjectable() .getGlobalSecurityPolicyRef()); @@ -369,7 +359,7 @@ public void testAddGetSystemConfigFile() throws Exception { // THEN repoSystemConfig = repositoryService.getObject(SystemConfigurationType.class, systemCongigOid, null, result); - LOGGER.info("system config after modify: {}", repoSystemConfig.debugDump()); + logger.info("system config after modify: {}", repoSystemConfig.debugDump()); AssertJUnit.assertNotNull("global security policy null", repoSystemConfig.asObjectable().getGlobalSecurityPolicyRef()); } @@ -514,7 +504,6 @@ public boolean handle(PrismObject object, OperationResult parentResu @Test private void addGetFullAccountShadow() throws Exception { - LOGGER.info("===[ simpleAddAccountShadowTest ]==="); OperationResult result = new OperationResult("testAddAccountShadow"); File file = new File(FOLDER_BASIC, "account-accountTypeShadow.xml"); try { @@ -531,7 +520,7 @@ private void addGetFullAccountShadow() throws Exception { AssertJUnit.assertNotNull(afterAdd); } catch (Exception ex) { - LOGGER.error("Exception occurred", ex); + logger.error("Exception occurred", ex); throw ex; } } @@ -576,7 +565,7 @@ public void test100AddUserWithoutAssignmentIds() throws Exception { } Collections.sort(dbShorts); - LOGGER.info("assigments ids: expected {} db {}", Arrays.toString(xmlShorts.toArray()), + logger.info("assigments ids: expected {} db {}", Arrays.toString(xmlShorts.toArray()), Arrays.toString(dbShorts.toArray())); AssertJUnit.assertArrayEquals(xmlShorts.toArray(), dbShorts.toArray()); } finally { @@ -646,7 +635,7 @@ public void test201WatcherOverwriteWithOidNoVersion() throws Exception { @Test public void test202WatcherOverwriteWithOidNoVersion2() throws Exception { - OperationResult result = new OperationResult("test202WatcherOverwriteWithOidNoVersion2"); + OperationResult result = createOperationResult(); // GIVEN UserType user = new UserType(prismContext).name("t200").oid(OID_200); @@ -665,7 +654,7 @@ public void test202WatcherOverwriteWithOidNoVersion2() throws Exception { @Test public void test203WatcherOverwriteWithOidAndVersion() throws Exception { - OperationResult result = new OperationResult("test203WatcherOverwriteWithOidAndVersion"); + OperationResult result = createOperationResult(); // GIVEN UserType user = new UserType(prismContext).name("t200").oid(OID_200).version("1000"); @@ -684,7 +673,7 @@ public void test203WatcherOverwriteWithOidAndVersion() throws Exception { @Test public void test210WatcherAddWithOidAndVersion() throws Exception { - OperationResult result = new OperationResult("test210WatcherAddWithOidAndVersion"); + OperationResult result = createOperationResult(); // GIVEN final String OID = "f82cdad5-8748-43c1-b20b-7f679fbc1995"; @@ -704,7 +693,7 @@ public void test210WatcherAddWithOidAndVersion() throws Exception { @Test public void test220WatcherAddWithNoOidNorVersion() throws Exception { - OperationResult result = new OperationResult("test220WatcherAddWithNoOidNorVersion"); + OperationResult result = createOperationResult(); // GIVEN UserType user = new UserType(prismContext).name("t220"); @@ -724,7 +713,7 @@ public void test220WatcherAddWithNoOidNorVersion() throws Exception { @Test public void test230WatcherAddWithVersion() throws Exception { - OperationResult result = new OperationResult("test230WatcherAddWithVersion"); + OperationResult result = createOperationResult(); // GIVEN UserType user = new UserType(prismContext).name("t230").version("2000"); @@ -744,7 +733,7 @@ public void test230WatcherAddWithVersion() throws Exception { @Test public void test300ContainerIds() throws Exception { - OperationResult result = new OperationResult("test300ContainerIds"); + OperationResult result = createOperationResult(); // GIVEN UserType user = new UserType(prismContext) @@ -767,7 +756,7 @@ public void test300ContainerIds() throws Exception { @Test public void test990AddResourceWithEmptyConnectorConfiguration() throws Exception { - OperationResult result = new OperationResult("test990AddResourceWithEmptyConnectorConfiguration"); + OperationResult result = createOperationResult(); PrismObject prismResource = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ResourceType.class).instantiate(); @@ -807,7 +796,7 @@ public void test400AddModifyTask() throws Exception { TaskType taskType = task.asObjectable(); AssertJUnit.assertNotNull(taskType.getResult()); - OperationResult result = new OperationResult("test400AddTask"); + OperationResult result = createOperationResult(); String oid = repositoryService.addObject(task, null, result); Session session = null; diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddOverwriteTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddOverwriteTest.java index 41205797fb8..58970525274 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddOverwriteTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddOverwriteTest.java @@ -54,7 +54,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class AddOverwriteTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(AddOverwriteTest.class); private static final String ORG_STRUCT_OBJECTS = "src/test/resources/orgstruct/org-monkey-island.xml"; private static final String IMPORT_OVERWRITE = "src/test/resources/basic/import-overwrite.xml"; private static final File RESOURCE_OPENDJ_FILE = new File("src/test/resources/basic/resource-opendj.xml"); @@ -62,12 +61,6 @@ public class AddOverwriteTest extends BaseSQLRepoTest { private static final String ORG_OID = "00000000-8888-6666-0000-100000000001"; - @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { - PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - @Test public void addWithOverwrite() throws Exception { List> objects = prismContext.parserFor(new File(ORG_STRUCT_OBJECTS)).parseObjects(); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditCleanupPerformanceTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditCleanupPerformanceTest.java index 3fe9df71d63..12bab80ae4f 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditCleanupPerformanceTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditCleanupPerformanceTest.java @@ -7,6 +7,15 @@ package com.evolveum.midpoint.repo.sql; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.repo.sql.data.audit.RAuditEventRecord; @@ -15,18 +24,8 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.test.NullTaskImpl; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.CleanupPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.hibernate.Session; -import org.hibernate.query.Query; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import java.util.List; /** * @author lazyman @@ -36,8 +35,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class AuditCleanupPerformanceTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(AuditCleanupPerformanceTest.class); - private static final int RECORDS = 50000; private static final boolean DO_CREATE = true; diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditTest.java index b6549ac315b..1e42077b7dc 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AuditTest.java @@ -7,6 +7,19 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.audit.api.AuditEventType; @@ -15,33 +28,18 @@ import com.evolveum.midpoint.repo.sql.data.audit.RAuditEventRecord; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.task.api.test.NullTaskImpl; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.util.*; - -import static org.testng.AssertJUnit.assertEquals; /** * @author mederly */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class AuditTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(AuditTest.class); - @Test - public void test100AuditSimple() throws Exception { - LOGGER.info("===[ test100AuditSimple ]==="); - + public void test100AuditSimple() { // WHEN AuditEventRecord record = new AuditEventRecord(); record.addPropertyValue("prop1", "val1.1"); @@ -56,7 +54,7 @@ public void test100AuditSimple() throws Exception { record.addReferenceValue("ref1", refVal1_2); record.addReferenceValue("ref2", refVal2); record.addReferenceValue("ref3", refVal3); - LOGGER.info("Adding audit record {}", record); + logger.info("Adding audit record {}", record); auditService.audit(record, new NullTaskImpl()); // THEN @@ -81,13 +79,11 @@ private PolyString poly(String orig) { } @Test - public void test110AuditSecond() throws Exception { - LOGGER.info("===[ test110AuditSecond ]==="); - + public void test110AuditSecond() { // WHEN AuditEventRecord record = new AuditEventRecord(); record.addPropertyValue("prop", "val"); - LOGGER.info("Adding audit record {}", record); + logger.info("Adding audit record {}", record); auditService.audit(record, new NullTaskImpl()); // THEN diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java index 507cc2166e0..72b4fd515eb 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/BaseSQLRepoTest.java @@ -18,6 +18,7 @@ import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import javax.xml.namespace.QName; import org.hibernate.Session; @@ -27,7 +28,8 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.testng.AssertJUnit; -import org.testng.annotations.*; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeSuite; import org.xml.sax.SAXException; import com.evolveum.midpoint.audit.api.AuditService; @@ -56,22 +58,18 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author lazyman - */ -public class BaseSQLRepoTest extends AbstractSpringTest { - - private static final Trace LOGGER = TraceManager.getTrace(BaseSQLRepoTest.class); +public class BaseSQLRepoTest extends AbstractSpringTest + implements OperationResultTestMixin { static final File FOLDER_BASE = new File("./src/test/resources"); @@ -113,7 +111,7 @@ public class BaseSQLRepoTest extends AbstractSpringTest { protected boolean verbose = false; @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { + public void prismContextForTestSuite() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } @@ -128,32 +126,15 @@ public void setFactory(SessionFactory factory) { this.factory = factory; } - @BeforeClass - public void beforeClass() throws Exception { - System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> START " + getClass().getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> START {} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName() }); - } - - @AfterClass - public void afterClass() { - System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> FINISH " + getClass().getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> FINISH {} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName() }); - } - private volatile boolean initSystemExecuted = false; - // TODO inttest: consider @PostConstruct like in AbstractIntegrationTest - @BeforeMethod - public void beforeMethod(Method method) throws Exception { + @PostConstruct + public void beforeMethod() throws Exception { if (initSystemExecuted) { logger.trace("initSystem: already called for class {} - IGNORING", getClass().getName()); return; } initSystemExecuted = true; - System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> START TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - logger.info(">>>>>>>>>>>>>>>>>>>>>>>> START {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", - getClass().getName(), method.getName()); - initSystem(); } @@ -167,11 +148,8 @@ public void afterMethod(Method method) { } } catch (Exception ex) { //it's ok - LOGGER.debug("after test method, checking for potential open session, exception occurred: " + ex.getMessage()); + logger.debug("after test method, checking for potential open session, exception occurred: " + ex.getMessage()); } - - System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> END TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); - LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> END {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[] { getClass().getName(), method.getName() }); } protected boolean isH2() { @@ -220,15 +198,6 @@ protected PrismObject getObject(Class type, String return object; } - protected OperationResult createResult() { - return new OperationResult(contextName()); - } - - // TODO: merge with similar methods in AbstractIntegrationTest - protected void display(String message, PrismObject object) { - System.out.println("\n" + message + "\n" + object.debugDump(1)); - } - protected S_ItemEntry deltaFor(Class objectClass) throws SchemaException { return prismContext.deltaFor(objectClass); } @@ -327,8 +296,16 @@ protected void assertSearch(ItemName item, String value, int expectedCount, Oper SearchResultList> found = repositoryService .searchObjects(UserType.class, query, null, result); if (verbose) { - PrismTestUtil.display("Found", found); + display("Found", found); } assertEquals("Wrong # of objects found", expectedCount, found.size()); } + + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CertificationTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CertificationTest.java index 07390170b00..4c17cb66583 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CertificationTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CertificationTest.java @@ -27,8 +27,6 @@ import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -56,14 +54,10 @@ import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; import static org.testng.AssertJUnit.*; -/** - * @author mederly - */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class CertificationTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(CertificationTest.class); private static final File TEST_DIR = new File("src/test/resources/cert"); public static final File CAMPAIGN_1_FILE = new File(TEST_DIR, "cert-campaign-1.xml"); public static final File CAMPAIGN_2_FILE = new File(TEST_DIR, "cert-campaign-2.xml"); @@ -207,7 +201,7 @@ public void test240AddCases() throws Exception { @Test public void test250DeleteCase() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject campaign10Before = getFullCampaign(campaign1Oid); display("Campaign 10 before", campaign10Before); @@ -555,7 +549,7 @@ private void addUnansweredActiveCases(List expected } } if (emptyDecisionFound) { - LOGGER.info("Expecting case of {}:{}", campaign.getOid(), aCase.getId()); + logger.info("Expecting case of {}:{}", campaign.getOid(), aCase.getId()); expectedCases.add(aCase); } } @@ -643,7 +637,7 @@ private void assertWorkItemsCount(Integer expected, List getOwningCampaignChecked(AccessCertificationCaseType aCase) { PrismContainer caseContainer = (PrismContainer) aCase.asPrismContainerValue().getParent(); assertNotNull("campaign is not fetched (case parent is null)", caseContainer); - PrismContainerValue campaignValue = (PrismContainerValue) caseContainer.getParent(); + PrismContainerValue campaignValue = caseContainer.getParent(); assertNotNull("campaign is not fetched (case container parent is null)", caseContainer); PrismObject campaign = (PrismObject) campaignValue.getParent(); assertNotNull("campaign is not fetched (campaign PCV parent is null)", campaign); @@ -679,7 +673,7 @@ private void checkCampaign(String campaignOid, OperationResult result, PrismObje ItemDeltaCollectionsUtil.applyTo(modifications, expectedObject); } - LOGGER.trace("Expected object = \n{}", expectedObject.debugDump()); + logger.trace("Expected object = \n{}", expectedObject.debugDump()); boolean casesExpected = !expectedObject.asObjectable().getCase().isEmpty(); @@ -689,7 +683,7 @@ private void checkCampaign(String campaignOid, OperationResult result, PrismObje assertFalse("campaign.case is marked as incomplete", caseContainerFull.isIncomplete()); } - LOGGER.trace("Actual object from repo = \n{}", campaignFull.debugDump()); + logger.trace("Actual object from repo = \n{}", campaignFull.debugDump()); PrismAsserts.assertEquivalent("Campaign is not as expected", expectedObject, campaignFull); if (expectedVersion != null) { diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CleanupTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CleanupTest.java index 935b246db41..57da9ea54ce 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CleanupTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/CleanupTest.java @@ -15,8 +15,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.test.NullTaskImpl; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.CleanupPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; @@ -36,15 +34,10 @@ import java.util.Date; import java.util.List; -/** - * @author lazyman - */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class CleanupTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(CleanupTest.class); - private Calendar create_2013_07_12_12_00_Calendar() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, 2013); @@ -72,18 +65,17 @@ private CleanupPolicyType createPolicy(Calendar when, long now) throws Exception return policy; } - private CleanupPolicyType createPolicy(int maxRecords) throws Exception { + private CleanupPolicyType createPolicy(int maxRecords) { CleanupPolicyType policy = new CleanupPolicyType(); - policy.setMaxRecords(Integer.valueOf(maxRecords)); + policy.setMaxRecords(maxRecords); return policy; } @AfterMethod public void cleanup() { - Session session = getFactory().openSession(); - try { + try (Session session = getFactory().openSession()) { session.beginTransaction(); session.createQuery("delete from RObjectDeltaOperation").executeUpdate(); session.createQuery("delete from RAuditPropertyValue").executeUpdate(); @@ -95,8 +87,6 @@ public void cleanup() { AssertJUnit.assertEquals(0L, (long) count); session.getTransaction().commit(); - } finally { - session.close(); } } @@ -139,7 +129,6 @@ public void testAuditCleanupMaxRecords() throws Exception { calendar.add(Calendar.HOUR_OF_DAY, 1); calendar.add(Calendar.MINUTE, 1); - final long NOW = System.currentTimeMillis(); CleanupPolicyType policy = createPolicy(1); OperationResult result = new OperationResult("Cleanup audit"); @@ -147,8 +136,7 @@ public void testAuditCleanupMaxRecords() throws Exception { result.recomputeStatus(); //THEN - RAuditEventRecord record = assertAndReturnAuditEventRecord(result); - + assertAndReturnAuditEventRecord(result); } private RAuditEventRecord assertAndReturnAuditEventRecord(OperationResult result) { @@ -179,7 +167,7 @@ private void prepareAuditEventRecords() throws Exception { record.setTimestamp(timestamp); record.addPropertyValue("prop1", "val1"); record.addReferenceValue("ref1", ObjectTypeUtil.createObjectRef("oid1", ObjectTypes.USER).asReferenceValue()); - LOGGER.info("Adding audit record with timestamp {}", new Object[]{new Date(timestamp)}); + logger.info("Adding audit record with timestamp {}", new Object[]{new Date(timestamp)}); auditService.audit(record, new NullTaskImpl()); calendar.add(Calendar.HOUR_OF_DAY, 1); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ConcurrencyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ConcurrencyTest.java index 30cad58a763..ebabbc018aa 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ConcurrencyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ConcurrencyTest.java @@ -7,11 +7,29 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import javax.xml.namespace.QName; + +import org.hibernate.Session; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.repo.sql.testing.SqlRepoTestUtil; import com.evolveum.midpoint.schema.SearchResultList; @@ -19,51 +37,24 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -import org.hibernate.Session; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; - -import static org.testng.AssertJUnit.*; - /** * @author Pavol Mederly */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ConcurrencyTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(ConcurrencyTest.class); - private static final long WAIT_FOR_THREAD_NATURAL_STOP_TIME = 300000; - //private static final long WAIT_STEP = 500; @Test public void test001TwoWriters_OneAttributeEach__NoReader() throws Exception { PropertyModifierThread[] mts = new PropertyModifierThread[] { new PropertyModifierThread(1, UserType.F_GIVEN_NAME, true, null, true), new PropertyModifierThread(2, UserType.F_FAMILY_NAME, true, null, true), -// new ModifierThread(3, oid, UserType.F_DESCRIPTION, false), -// new ModifierThread(4, oid, UserType.F_EMAIL_ADDRESS, false), -// new ModifierThread(5, oid, UserType.F_TELEPHONE_NUMBER, false), -// new ModifierThread(6, oid, UserType.F_EMPLOYEE_NUMBER, false), -// new ModifierThread(8, oid, UserType.F_EMAIL_ADDRESS), -// new ModifierThread(9, oid, UserType.F_EMPLOYEE_NUMBER) }; concurrencyUniversal("Test1", 30000L, 500L, mts, null); } @@ -90,10 +81,10 @@ public void test003OneWriter_TwoAttributes__OneReader() throws Exception { PrismObject userRetrieved = repositoryService.getObject(UserType.class, oid, null, new OperationResult("dummy")); String givenName = userRetrieved.asObjectable().getGivenName().getOrig(); String assignmentDescription = userRetrieved.asObjectable().getAssignment().get(0).getDescription(); - LOGGER.info("[" + iteration + "] givenName = " + givenName + ", assignment description = " + assignmentDescription); + logger.info("[" + iteration + "] givenName = " + givenName + ", assignment description = " + assignmentDescription); if (!givenName.equals(assignmentDescription)) { String msg = "Inconsistent object state: GivenName = " + givenName + ", assignment description = " + assignmentDescription; - LOGGER.error(msg); + logger.error(msg); throw new AssertionError(msg); } }; @@ -116,15 +107,15 @@ public void test004TwoWriters_TwoAttributesEach__OneReader() throws Exception { String familyName = userRetrieved.asObjectable().getFamilyName().getOrig(); String assignmentDescription = userRetrieved.asObjectable().getAssignment().get(0).getDescription(); String referenceDescription = userRetrieved.asObjectable().getAssignment().get(0).getConstruction().getDescription(); - LOGGER.info("[" + iteration + "] givenName = " + givenName + ", assignment description = " + assignmentDescription + ", familyName = " + familyName + ", referenceDescription = " + referenceDescription); + logger.info("[" + iteration + "] givenName = " + givenName + ", assignment description = " + assignmentDescription + ", familyName = " + familyName + ", referenceDescription = " + referenceDescription); if (!givenName.equals(assignmentDescription)) { String msg = "Inconsistent object state: GivenName = " + givenName + ", assignment description = " + assignmentDescription; - LOGGER.error(msg); + logger.error(msg); throw new AssertionError(msg); } if (!familyName.equals(referenceDescription)) { String msg = "Inconsistent object state: FamilyName = " + familyName + ", account construction description = " + referenceDescription; - LOGGER.error(msg); + logger.error(msg); throw new AssertionError(msg); } }; @@ -149,15 +140,15 @@ private void concurrencyUniversal(String name, long duration, long waitStep, Pro OperationResult result = new OperationResult("Concurrency Test"); String oid = repositoryService.addObject(user, null, result); - LOGGER.info("*** Object added: {} ***", oid); - LOGGER.info("*** Starting modifier threads ***"); + logger.info("*** Object added: {} ***", oid); + logger.info("*** Starting modifier threads ***"); for (PropertyModifierThread mt : modifierThreads) { mt.setObject(UserType.class, oid); mt.start(); } - LOGGER.info("*** Waiting {} ms ***", duration); + logger.info("*** Waiting {} ms ***", duration); long startTime = System.currentTimeMillis(); int readIteration = 1; main: @@ -170,7 +161,7 @@ private void concurrencyUniversal(String name, long duration, long waitStep, Pro } for (PropertyModifierThread mt : modifierThreads) { if (!mt.isAlive()) { - LOGGER.error("At least one of threads died prematurely, finishing waiting."); + logger.error("At least one of threads died prematurely, finishing waiting."); break main; } } @@ -180,7 +171,7 @@ private void concurrencyUniversal(String name, long duration, long waitStep, Pro for (PropertyModifierThread mt : modifierThreads) { mt.stop = true; // stop the threads System.out.println("Thread " + mt.id + " has done " + mt.counter.get() + " iterations"); - LOGGER.info("Thread " + mt.id + " has done " + mt.counter.get() + " iterations"); + logger.info("Thread " + mt.id + " has done " + mt.counter.get() + " iterations"); } // we do not have to wait for the threads to be stopped, just examine their results @@ -188,7 +179,7 @@ private void concurrencyUniversal(String name, long duration, long waitStep, Pro Thread.sleep(1000); // give the threads a chance to finish (before repo will be shut down) for (PropertyModifierThread mt : modifierThreads) { - LOGGER.info("Modifier thread {} finished with an exception", mt.id, mt.threadResult); + logger.info("Modifier thread {} finished with an exception", mt.id, mt.threadResult); } for (PropertyModifierThread mt : modifierThreads) { @@ -224,17 +215,18 @@ public void run() { try { while (!stop && (limit == null || counter.intValue() < limit)) { OperationResult result = new OperationResult("run"); - LOGGER.info(" --- Iteration number {} for {} ---", counter.incrementAndGet(), description()); + logger.info(" --- Iteration number {} for {} ---", counter.incrementAndGet(), description()); runOnce(result); } } catch (Throwable t) { - LoggingUtils.logException(LOGGER, "Got exception: " + t, t); + LoggingUtils.logException(logger, "Got exception: " + t, t); threadResult = t; } } abstract void runOnce(OperationResult result) throws Exception; abstract String description(); + public void setObject(Class objectClass, String oid) { this.objectClass = objectClass; this.oid = oid; @@ -326,7 +318,7 @@ void runOnce(OperationResult result) { repositoryService.modifyObject(UserType.class, oid, deltas, result); result.computeStatus(); if (result.isError()) { - LOGGER.error("Error found in operation result:\n{}", result.debugDump()); + logger.error("Error found in operation result:\n{}", result.debugDump()); throw new IllegalStateException("Error found in operation result"); } } catch (Exception e) { @@ -361,21 +353,21 @@ void runOnce(OperationResult result) { if (!dataWritten.equals(dataRead)) { threadResult = new RuntimeException("Data read back (" + dataRead + ") does not match the data written (" + dataWritten + ") on attribute " + attribute1); - LOGGER.error("compare failed", threadResult); + logger.error("compare failed", threadResult); stop = true; return; } if (attribute2 != null) { if (ConstructionType.COMPLEX_TYPE.equals(propertyDefinition2.getTypeName())) { - dataRead = ((ConstructionType)user.findContainer(attribute2).getValue().getValue()).getDescription(); + dataRead = ((ConstructionType) user.findContainer(attribute2).getValue().getValue()).getDescription(); } else { dataRead = user.findProperty(attribute2).getRealValue(String.class); } if (!dataWritten.equals(dataRead)) { threadResult = new RuntimeException("Data read back (" + dataRead + ") does not match the data written (" + dataWritten + ") on attribute " + attribute2); - LOGGER.error("compare failed", threadResult); + logger.error("compare failed", threadResult); stop = true; return; } @@ -385,7 +377,7 @@ void runOnce(OperationResult result) { String versionError = SqlRepoTestUtil.checkVersionProgress(lastVersion, currentVersion); if (versionError != null) { threadResult = new RuntimeException(versionError); - LOGGER.error(versionError); + logger.error(versionError); stop = true; return; } @@ -445,7 +437,6 @@ void runOnce(OperationResult result) throws Exception { protected abstract String getOidToDelete(); } - abstract class DeltaExecutionThread extends WorkerThread { String description; @@ -484,18 +475,18 @@ public void test010SearchIterative() throws Exception { repositoryService.searchObjectsIterative(UserType.class, prismContext.queryFor(UserType.class) - .item(UserType.F_NAME).eqPoly(name).matchingOrig().build(), + .item(UserType.F_NAME).eqPoly(name).matchingOrig().build(), (object, parentResult) -> { - LOGGER.info("Handling " + object + "..."); + logger.info("Handling " + object + "..."); ObjectDelta delta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, object.getOid(), - UserType.F_FULL_NAME, new PolyString(newFullName)); + UserType.F_FULL_NAME, new PolyString(newFullName)); try { //noinspection unchecked repositoryService.modifyObject(UserType.class, - object.getOid(), - delta.getModifications(), - parentResult); + object.getOid(), + delta.getModifications(), + parentResult); } catch (Exception e) { throw new RuntimeException("Exception in handle method", e); } @@ -526,9 +517,9 @@ public void test100AddOperationExecution() throws Exception { OperationResult result = new OperationResult("test100AddOperationExecution"); String oid = repositoryService.addObject(user.asPrismObject(), null, result); - PrismTestUtil.display("object added", oid); + display("object added", oid); - LOGGER.info("Starting worker threads"); + logger.info("Starting worker threads"); List threads = new ArrayList<>(); for (int i = 0; i < THREADS; i++) { @@ -581,9 +572,9 @@ public void test110AddAssignments() throws Exception { OperationResult result = new OperationResult("test110AddAssignments"); String oid = repositoryService.addObject(user.asPrismObject(), null, result); - PrismTestUtil.display("object added", oid); + display("object added", oid); - LOGGER.info("Starting worker threads"); + logger.info("Starting worker threads"); List threads = new ArrayList<>(); for (int i = 0; i < THREADS; i++) { @@ -620,9 +611,9 @@ public void test120AddApproverRef() throws Exception { OperationResult result = new OperationResult("test120AddApproverRef"); String oid = repositoryService.addObject(role.asPrismObject(), null, result); - PrismTestUtil.display("object added", oid); + display("object added", oid); - LOGGER.info("Starting worker threads"); + logger.info("Starting worker threads"); List threads = new ArrayList<>(); for (int i = 0; i < THREADS; i++) { @@ -689,7 +680,7 @@ public void test130AddDeleteObjects() throws Exception { assertEquals("Wrong # of users at the beginning", 0, repositoryService.countObjects(UserType.class, null, null, result)); - LOGGER.info("Starting ADD worker threads"); + logger.info("Starting ADD worker threads"); repositoryService.getPerformanceMonitor().clearGlobalPerformanceInformation(); List> addThreads = new ArrayList<>(); @@ -711,7 +702,7 @@ protected PrismObject getObjectToAdd() { .searchObjects(UserType.class, null, null, result); assertEquals("Wrong # of users after creation", ADD_THREADS * OBJECTS_PER_THREAD, objectsCreated.size()); - LOGGER.info("Starting DELETE worker threads"); + logger.info("Starting DELETE worker threads"); repositoryService.getPerformanceMonitor().clearGlobalPerformanceInformation(); AtomicInteger objectsPointer = new AtomicInteger(0); @@ -739,7 +730,7 @@ protected String getOidToDelete() { } private void waitForThreadsFinish(List threads, long timeout) throws InterruptedException { - LOGGER.info("*** Waiting until finish, at most {} ms ***", timeout); + logger.info("*** Waiting until finish, at most {} ms ***", timeout); long startTime = System.currentTimeMillis(); main: while (System.currentTimeMillis() - startTime < timeout) { @@ -759,14 +750,14 @@ private void waitForThreadsFinish(List threads, long tim } private void waitForThreads(List threads, long duration) throws InterruptedException { - LOGGER.info("*** Waiting {} ms ***", duration); + logger.info("*** Waiting {} ms ***", duration); long startTime = System.currentTimeMillis(); main: while (System.currentTimeMillis() - startTime < duration) { for (WorkerThread thread : threads) { if (!thread.isAlive()) { - LOGGER.error("At least one of threads died prematurely, finishing waiting."); + logger.error("At least one of threads died prematurely, finishing waiting."); break main; } } @@ -777,7 +768,7 @@ private void waitForThreads(List threads, long duration) for (WorkerThread thread : threads) { thread.stop = true; // stop the threads System.out.println("Thread " + thread.id + " has done " + thread.counter.get() + " iterations"); - LOGGER.info("Thread " + thread.id + " has done " + thread.counter.get() + " iterations"); + logger.info("Thread " + thread.id + " has done " + thread.counter.get() + " iterations"); } long start = System.currentTimeMillis(); @@ -790,7 +781,7 @@ private void waitForThreads(List threads, long duration) assertTrue("Some threads had not stopped in given time: " + alive, alive.isEmpty()); for (WorkerThread thread : threads) { - LOGGER.info("Modifier thread " + thread.id + " finished with an exception: ", thread.threadResult); + logger.info("Modifier thread " + thread.id + " finished with an exception: ", thread.threadResult); } for (WorkerThread thread : threads) { @@ -803,5 +794,4 @@ private void waitForThreads(List threads, long duration) private SqlRepositoryConfiguration getConfiguration() { return ((SqlRepositoryServiceImpl) repositoryService).getConfiguration(); } - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DataSourceTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DataSourceTest.java index e163abe68e9..3ed9e5f1343 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DataSourceTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DataSourceTest.java @@ -12,6 +12,7 @@ import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; + /** * @author lazyman */ diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTest.java index 4dfd41ccd89..0bfda38a166 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTest.java @@ -10,8 +10,6 @@ import com.evolveum.midpoint.prism.Objectable; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; @@ -33,13 +31,11 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class DeleteTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(DeleteTest.class); - @Test public void delete001() throws Exception { final File file = new File("./../../samples/dsee/odsee-localhost-advanced-sync.xml"); if (!file.exists()) { - LOGGER.warn("skipping addGetDSEESyncDoubleTest, file {} not found.", + logger.warn("skipping addGetDSEESyncDoubleTest, file {} not found.", new Object[]{file.getPath()}); return; } @@ -50,13 +46,13 @@ public void delete001() throws Exception { OperationResult result = new OperationResult("Delete Test"); for (int i = 0; i < elements.size(); i++) { PrismObject object = elements.get(i); - LOGGER.info("Adding object {}, type {}", new Object[]{i, object.getCompileTimeClass().getSimpleName()}); + logger.info("Adding object {}, type {}", new Object[]{i, object.getCompileTimeClass().getSimpleName()}); oids.add(repositoryService.addObject(object, null, result)); } for (int i = 0; i < elements.size(); i++) { PrismObject object = elements.get(i); - LOGGER.info("Deleting object {}, type {}", new Object[]{i, object.getCompileTimeClass().getSimpleName()}); + logger.info("Deleting object {}, type {}", new Object[]{i, object.getCompileTimeClass().getSimpleName()}); repositoryService.deleteObject(object.getCompileTimeClass(), oids.get(i), result); } @@ -90,21 +86,17 @@ public void delete0003() throws Exception { AssertJUnit.assertTrue(result.isSuccess()); - Session session = getFactory().openSession(); - try { - Query query = session.createNativeQuery("select count(*) from m_trigger where owner_oid = ?"); + try (Session session = getFactory().openSession()) { + Query query = session.createNativeQuery("select count(*) from m_trigger where owner_oid = ?"); query.setParameter(1, oid); Number count = (Number) query.uniqueResult(); AssertJUnit.assertEquals(count.longValue(), 0L); - } finally { - session.close(); } } @Test public void test100DeleteObjects() throws Exception { -// PrismDomProcessor domProcessor = prismContext.getPrismDomProcessor(); List> objects = prismContext.parserFor(new File(FOLDER_BASIC, "objects.xml")).parseObjects(); OperationResult result = new OperationResult("add objects"); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTestSimple.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTestSimple.java index 22b67489ceb..77560669091 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTestSimple.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/DeleteTestSimple.java @@ -9,8 +9,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -18,40 +16,17 @@ import java.io.File; -/** - * @author mederly - */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class DeleteTestSimple extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(DeleteTestSimple.class); - @Test public void delete001() throws Exception { PrismObject user = prismContext.parseObject(new File(FOLDER_BASIC, "user0.xml")); OperationResult result = new OperationResult("Delete Test"); String oid = repositoryService.addObject(user, null, result); - LOGGER.info("*** deleteObject ***"); - - // Session session = open(); - // CriteriaQuery aQ = session.getCriteriaBuilder().createQuery(RAssignment.class); - // aQ.select(aQ.from(RAssignment.class)); - // List aList = session.createQuery(aQ).getResultList(); - // System.out.println("RAssignment: " + aList); - // - // CriteriaQuery aeQ = session.getCriteriaBuilder().createQuery(RAssignmentExtension.class); - // aeQ.select(aeQ.from(RAssignmentExtension.class)); - // List aeList = session.createQuery(aeQ).getResultList(); - // System.out.println("RAssignmentExtension: " + aeList); - // - // CriteriaQuery aebQ = session.getCriteriaBuilder().createQuery(RAExtBoolean.class); - // aebQ.select(aebQ.from(RAExtBoolean.class)); - // List aebList = session.createQuery(aebQ).getResultList(); - // System.out.println("RAExtBoolean: " + aebList); - // - // session.getTransaction().commit(); + logger.info("*** deleteObject ***"); repositoryService.deleteObject(UserType.class, oid, result); } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EmbeddedServerModeTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EmbeddedServerModeTest.java index 032c25745e2..ca5be97f4d7 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EmbeddedServerModeTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EmbeddedServerModeTest.java @@ -7,8 +7,6 @@ package com.evolveum.midpoint.repo.sql; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -18,21 +16,16 @@ import java.sql.Connection; import java.sql.DriverManager; -/** - * @author lazyman - */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class EmbeddedServerModeTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(EmbeddedServerModeTest.class); - @Autowired - SqlRepositoryFactory sqlFactory; + private SqlRepositoryFactory sqlFactory; @Test public void testServerMode() throws Exception { - LOGGER.info("testServerMode"); + logger.info("testServerMode"); Connection connection = null; try { diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EncodingTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EncodingTest.java index de8bffce803..02f5cda8ad7 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EncodingTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/EncodingTest.java @@ -7,6 +7,15 @@ package com.evolveum.midpoint.repo.sql; +import java.util.Collection; +import java.util.List; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismProperty; @@ -19,31 +28,14 @@ import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.RandomString; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; - -import java.util.Collection; -import java.util.List; - -/** - * @author lazyman - */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class EncodingTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(EncodingTest.class); - /** * Long text with national characters. This is used to test whether the database can store a long text * and that it maintains national characters. @@ -477,8 +469,8 @@ public class EncodingTest extends BaseSQLRepoTest { private static final String USER_FULL_NAME = "Grăfula Fèlix Teleke z Tölökö"; private static final String USER_GIVEN_NAME = "P\u00f3lic\u00edja, p\u00f3lic\u00edja, S\u00e1la\u0161\u00e1ry, pr\u00e1va Jova. Z c\u00e9sty pr\u00edva, z c\u00e9sty pr\u00e1va, s\u00fdmpatika, korpora. Popul\u00e1ry, Karpatula. Juv\u00e1 svorno polic\u00e1na. Kerl\u00e9\u0161 na strach, polic\u00edja. Bumtar\u00e1ra, bumtar\u00e1ra, bum. ";//"Fëľïx"; private static final String USER_FAMILY_NAME = "ŢæĺêkéčišćeľščťžýáíéäöåøřĺąćęłńóśźżrůāēīūŗļķņģšžčāäǟḑēīļņōȯȱõȭŗšțūžÇĞIİÖŞÜáàâéèêíìîóòôúùûáâãçéêíóôõúÁ᥹ÄäÉéĘęĚěÍíÓóÔôÚúŮůÝýČčĎĽľĹĺŇňŔŕŘřŠšŽž"; - private static final String[] USER_ORGANIZATION = {"COMITATVS NOBILITVS HVNGARIÆ", "Salsa Verde ğomorula prïvatûła"}; - private static final String[] USER_SUBTYPE = {"Ģŗąfųŀą", "CANTATOR"}; + private static final String[] USER_ORGANIZATION = { "COMITATVS NOBILITVS HVNGARIÆ", "Salsa Verde ğomorula prïvatûła" }; + private static final String[] USER_SUBTYPE = { "Ģŗąfųŀą", "CANTATOR" }; private static final String INSANE_NATIONAL_STRING = "Pørúga ném nå väšȍm apârátula"; private RandomString randomString; @@ -487,7 +479,6 @@ public EncodingTest() { randomString = new RandomString(NAME_RANDOM_LENGTH, true); } - @Test public void repositorySelfTest() throws Exception { OperationResult testResult = new OperationResult("self test"); @@ -498,7 +489,7 @@ public void repositorySelfTest() throws Exception { testResult.computeStatus(); - LOGGER.info(testResult.debugDump()); + logger.info(testResult.debugDump()); System.out.println(testResult.debugDump()); AssertJUnit.assertEquals(OperationResultStatus.SUCCESS, testResult.getStatus()); } @@ -540,8 +531,8 @@ private void repositorySelfTestUser(OperationResult testResult) throws SchemaExc result.recordFatalError(e); return; } - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Self-test:user getObject:\n{}", userRetrieved.debugDump()); + if (logger.isTraceEnabled()) { + logger.trace("Self-test:user getObject:\n{}", userRetrieved.debugDump()); } checkUser(userRetrieved, name, subresult); subresult.recordSuccessIfUnknown(); @@ -553,8 +544,8 @@ private void repositorySelfTestUser(OperationResult testResult) throws SchemaExc .build(); subresult1.addParam("query", query); List> foundObjects = repositoryService.searchObjects(UserType.class, query, null, subresult1); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Self-test:user searchObjects:\n{}", DebugUtil.debugDump(foundObjects)); + if (logger.isTraceEnabled()) { + logger.trace("Self-test:user searchObjects:\n{}", DebugUtil.debugDump(foundObjects)); } assertSingleSearchResult("user", foundObjects, subresult1); @@ -564,22 +555,10 @@ private void repositorySelfTestUser(OperationResult testResult) throws SchemaExc subresult1.recordSuccessIfUnknown(); } catch (Exception e) { subresult1.recordFatalError(e); - return; } } finally { -// try { -// repositoryService.deleteObject(UserType.class, oid, testResult); -// } catch (ObjectNotFoundException e) { -// result.recordFatalError(e); -// return; -// } catch (RuntimeException e) { -// result.recordFatalError(e); -// return; -// } - result.computeStatus(); } - } private void assertSingleSearchResult(String objectTypeMessage, List> foundObjects, OperationResult parentResult) { @@ -600,7 +579,8 @@ private void checkUser(PrismObject userRetrieved, String name, Operati checkUserProperty(userRetrieved, UserType.F_DESCRIPTION, subresult, POLICIJA); } - private void checkUserProperty(PrismObject object, QName propQName, OperationResult parentResult, T... expectedValues) { + private void checkUserProperty(PrismObject object, + QName propQName, OperationResult parentResult, T... expectedValues) { String propName = propQName.getLocalPart(); OperationResult result = parentResult.createSubresult(parentResult.getOperation() + "." + propName); PrismProperty prop = object.findProperty(ItemName.fromQName(propQName)); @@ -630,7 +610,6 @@ private void assertMultivalue(String message, T[] expectedVals, Collection futures = new ArrayList<>(); + List> futures = new ArrayList<>(); for (Worker worker : workers) { worker.setIndex(i); futures.add(executors.submit(worker)); } - for (Future f : futures) { + for (Future f : futures) { f.get(); } @@ -83,35 +77,7 @@ public void testSerializationExceptions() throws Exception { executors.shutdownNow(); } -// private static class SelectWorker implements Runnable { -// -// private ExtDictionaryConcurrencyTest test; -// -// public SelectWorker(ExtDictionaryConcurrencyTest test) { -// this.test = test; -// } -// -// @Override -// public void run() { -// try { -// OperationResult result = new OperationResult("search"); -// -// SchemaRegistry registry = test.prismContext.getSchemaRegistry(); -// -// ObjectQuery query = ObjectQuery.createObjectQuery( -// SubstringFilter.createSubstring( -// .path(UserType.F_NAME), -// registry.findComplexTypeDefinitionByCompileTimeClass(UserType.class).findPropertyDefinition(UserType.F_NAME), -// test.prismContext, null, "worker", false, false)); -// List> res = test.repositoryService.searchObjects(UserType.class, query, new ArrayList<>(), result); -// LOGGER.info("Found {} users", res.size()); -// } catch (Exception ex) { -// LOGGER.error("Search exception", ex); -// } -// } -// } - - private static class Worker implements Runnable { + private class Worker implements Runnable { private ExtDictionaryConcurrencyTest test; @@ -121,7 +87,7 @@ private static class Worker implements Runnable { private int index; public Worker(ExtDictionaryConcurrencyTest test, Class type, - String oid, String attribute) { + String oid, String attribute) { this.test = test; this.type = type; this.oid = oid; @@ -134,12 +100,11 @@ public void setIndex(int index) { @Override public void run() { - LOGGER.info("Starting for oid {} index {}", oid, index); + logger.info("Starting for oid {} index {}", oid, index); OperationResult result = new OperationResult("Test: " + attribute + index); try { ItemPath path = ItemPath.create(UserType.F_EXTENSION, new QName(NAMESPACE, attribute + index)); -// ItemPath path = ItemPath.create(UserType.F_DESCRIPTION); ObjectDelta delta = test.prismContext.deltaFactory().object().createModificationAddProperty(type, oid, path, attribute + index); @@ -149,14 +114,14 @@ public void run() { String ps = (String) obj.getPropertyRealValue(path, String.class); AssertJUnit.assertEquals(attribute + index, ps); } catch (Exception ex) { - LOGGER.error("Exception", ex); + logger.error("Exception", ex); ex.printStackTrace(); AssertJUnit.fail(ex.getMessage()); } finally { result.computeStatus(); } - LOGGER.info("Finished for oid {} index {}", oid, index); + logger.info("Finished for oid {} index {}", oid, index); } } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtDictionaryTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtDictionaryTest.java index 129d6dfed7d..19d981d4b0b 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtDictionaryTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtDictionaryTest.java @@ -7,53 +7,34 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.fail; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.namespace.QName; + +import org.hibernate.Session; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.MutablePrismPropertyDefinition; import com.evolveum.midpoint.prism.PrismProperty; -import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.sql.data.common.any.RExtItem; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.hibernate.Session; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; - -import javax.xml.namespace.QName; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.testng.AssertJUnit.fail; -/** - * @author lazyman - */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ExtDictionaryTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(ExtDictionaryTest.class); private static final int ROUNDS = 50; private static final int THREADS = 10; private static final String NS_TEST = "http://test"; - @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { - PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - - class TestingThread extends Thread { + static class TestingThread extends Thread { Throwable throwable; TestingThread(Runnable target) { super(target); @@ -111,7 +92,7 @@ public void test100ParallelAdd() throws Exception { System.out.println("ext items: " + extItems.size()); for (RExtItem extItem : extItems) { System.out.println(extItem); - LOGGER.info("{}", extItem); + logger.info("{}", extItem); } session.close(); } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtensionTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtensionTest.java index c3d11cc0fca..ed4ccf29cf1 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtensionTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ExtensionTest.java @@ -6,6 +6,21 @@ */ package com.evolveum.midpoint.repo.sql; +import static java.util.Collections.singleton; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; +import static com.evolveum.midpoint.schema.constants.SchemaConstants.RI_ACCOUNT_OBJECT_CLASS; + +import java.io.File; +import java.util.*; +import javax.xml.namespace.QName; + +import org.hibernate.Session; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; @@ -19,27 +34,15 @@ import com.evolveum.midpoint.repo.sql.data.common.any.RAssignmentExtension; import com.evolveum.midpoint.repo.sql.data.common.any.RExtItem; import com.evolveum.midpoint.repo.sql.data.common.container.RAssignment; -import com.evolveum.midpoint.schema.*; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.RetrieveOption; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.processor.*; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.hibernate.Session; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; -import java.io.File; -import java.util.*; - -import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; -import static com.evolveum.midpoint.schema.constants.SchemaConstants.RI_ACCOUNT_OBJECT_CLASS; -import static java.util.Collections.singleton; -import static org.testng.AssertJUnit.*; /** * Comprehensive test for extension and attribute values processing. @@ -80,12 +83,8 @@ public class ExtensionTest extends BaseSQLRepoTest { private static final int ADD_VALUE_ITERATIONS = 100000; - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - + @Override + public void initSystem() throws Exception { itemHidden1 = createOrFindExtensionItemDefinition(UserType.class, EXT_HIDDEN1); itemHidden2 = createOrFindExtensionItemDefinition(UserType.class, EXT_HIDDEN2); itemHidden3 = createOrFindExtensionItemDefinition(UserType.class, EXT_HIDDEN3); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ListAccountShadowOwnerTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ListAccountShadowOwnerTest.java index e726e53853c..d99df992e7d 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ListAccountShadowOwnerTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ListAccountShadowOwnerTest.java @@ -11,16 +11,13 @@ import static org.testng.AssertJUnit.assertNull; import java.io.File; -import java.io.IOException; import java.util.Collection; import java.util.List; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; -import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; -import org.xml.sax.SAXException; import com.evolveum.midpoint.prism.Objectable; import com.evolveum.midpoint.prism.PrismObject; @@ -28,11 +25,7 @@ import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -46,14 +39,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ListAccountShadowOwnerTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(ListAccountShadowOwnerTest.class); - - @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { - PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - @Test public void listExistingOwner() throws Exception { OperationResult result = new OperationResult("List owner"); @@ -61,8 +46,7 @@ public void listExistingOwner() throws Exception { //insert sample data final File OBJECTS_FILE = new File(FOLDER_BASIC, "objects.xml"); List> elements = prismContext.parserFor(OBJECTS_FILE).parseObjects(); - for (int i = 0; i < elements.size(); i++) { - PrismObject object = elements.get(i); + for (PrismObject object : elements) { repositoryService.addObject(object, null, result); } @@ -85,7 +69,7 @@ public void listNonExistingOwner() throws Exception { @Test public void testLinkUnlink() throws Exception { - LOGGER.info("==[testLinkUnlink]=="); + logger.info("==[testLinkUnlink]=="); // GIVEN OperationResult result = new OperationResult("testLinkUnlink"); PrismObject user = PrismTestUtil.parseObject(new File(FOLDER_BASIC, "user.xml")); @@ -117,13 +101,7 @@ public void testLinkUnlink() throws Exception { assertNull("listAccountShadowOwner returned non-null value after unlink", accountOwnerOid); } - /** - * @param string - * @param userOid - * @param accountOwnerOid - */ private void assertEquals(String string, String userOid, PrismObject accountOwnerOid) { // TODO Auto-generated method stub - } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/LookupTableTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/LookupTableTest.java index d56e2cc532f..b4e9755b127 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/LookupTableTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/LookupTableTest.java @@ -7,6 +7,22 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.RetrieveOption.INCLUDE; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType.*; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType.F_ROW; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; + +import java.io.File; +import java.util.*; +import javax.xml.datatype.XMLGregorianCalendar; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.Containerable; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismObject; @@ -23,34 +39,16 @@ import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import javax.xml.datatype.XMLGregorianCalendar; -import java.io.File; -import java.io.IOException; -import java.util.*; - -import static com.evolveum.midpoint.schema.RetrieveOption.INCLUDE; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType.*; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType.F_ROW; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; -import static org.testng.AssertJUnit.*; /** * @author mederly */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class LookupTableTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(LookupTableTest.class); private static final File TEST_DIR = new File("src/test/resources/lookup"); private static final long TIMESTAMP_TOLERANCE = 10000L; @@ -99,7 +97,7 @@ public void test108AddTableOverwriteExisting() throws Exception { public void test200ModifyTableProperties() throws Exception { OperationResult result = new OperationResult("test200ModifyTableProperties"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_NAME).replace(new PolyString("Table 1", "table 1")) .asItemDeltas(); @@ -110,12 +108,12 @@ public void test200ModifyTableProperties() throws Exception { public void test210ModifyRowProperties() throws Exception { OperationResult result = new OperationResult("test210ModifyRowProperties"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW, 1, F_KEY).replace("key 1") .item(F_ROW, 2, F_VALUE).replace() .item(F_ROW, 3, F_LABEL).replace(new PolyString("label 3")) .item(F_ROW, 3, F_LAST_CHANGE_TIMESTAMP) - .replace(XmlTypeConverter.createXMLGregorianCalendar(createDate(99, 10, 10))) + .replace(XmlTypeConverter.createXMLGregorianCalendar(createDate(99, 10, 10))) .asItemDeltas(); executeAndCheckModification(modifications, result, 0, Arrays.asList("key 1", "2 key")); @@ -131,7 +129,7 @@ private Date createDate(int year, int month, int day) { public void test220AddRemoveValues() throws Exception { OperationResult result = new OperationResult("test220AddRemoveValues"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW, 1, F_VALUE).delete("first value") .item(F_ROW, 2, F_VALUE).add("value 2") .asItemDeltas(); @@ -142,7 +140,7 @@ public void test220AddRemoveValues() throws Exception { public void test222ReplaceKeyToNull() throws Exception { OperationResult result = new OperationResult("test222ReplaceKeyToNull"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW, 1, F_KEY).replace() .asItemDeltas(); repositoryService.modifyObject(LookupTableType.class, tableOid, modifications, null, result); @@ -152,7 +150,7 @@ public void test222ReplaceKeyToNull() throws Exception { public void test224DeleteKeyValue() throws Exception { OperationResult result = new OperationResult("test224DeleteKeyValue"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW, 1, F_KEY).delete("key 1") .asItemDeltas(); repositoryService.modifyObject(LookupTableType.class, tableOid, modifications, null, result); @@ -162,7 +160,7 @@ public void test224DeleteKeyValue() throws Exception { public void test226AddKeylessRow() throws Exception { OperationResult result = new OperationResult("test226AddKeylessRow"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).add(new LookupTableRowType()) .asItemDeltas(); repositoryService.modifyObject(LookupTableType.class, tableOid, modifications, null, result); @@ -174,7 +172,7 @@ public void test228AddKeylessRow2() throws Exception { LookupTableRowType row = new LookupTableRowType(); row.setValue("value"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).add(row) .asItemDeltas(); repositoryService.modifyObject(LookupTableType.class, tableOid, modifications, null, result); @@ -184,7 +182,7 @@ public void test228AddKeylessRow2() throws Exception { public void test230ModifyTableAndRow() throws Exception { OperationResult result = new OperationResult("test230ModifyTableAndRow"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_NAME).replace(new PolyString("Table 111", "table 111")) .item(F_ROW, 2, F_KEY).replace("key 2") .asItemDeltas(); @@ -210,7 +208,7 @@ public void test240AddRows() throws Exception { row4.setKey("key 4"); row4.setValue("value 4"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).add(rowNoId, rowNoId2, row4) .asItemDeltas(); @@ -232,7 +230,7 @@ public void test245AddDuplicateRows() throws Exception { row4.setKey("key 4"); row4.setValue("value 4 NEW"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).add(rowNoId, row4) .asItemDeltas(); @@ -248,7 +246,7 @@ public void test250DeleteRow() throws Exception { LookupTableRowType row3 = new LookupTableRowType(prismContext); row3.setId(3L); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).delete(row3) .asItemDeltas(); @@ -262,7 +260,7 @@ public void test252DeleteNonexistingRow() throws Exception { LookupTableRowType rowNoId = new LookupTableRowType(prismContext); rowNoId.setKey("non-existing-key"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).delete(rowNoId) .asItemDeltas(); @@ -293,7 +291,7 @@ public void test255AddDeleteRows() throws Exception { LookupTableRowType row4 = new LookupTableRowType(prismContext); row4.setId(4L); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).add(rowNoId, row5).delete(row4) .asItemDeltas(); @@ -310,7 +308,7 @@ public void test260ReplaceRowsExistingId() throws Exception { row5.setValue("value 5 plus"); row5.setLastChangeTimestamp(XmlTypeConverter.createXMLGregorianCalendar(createDate(99, 3, 10))); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).replace(row5) .asItemDeltas(); @@ -325,7 +323,7 @@ public void test265ReplaceRowsNewId() throws Exception { rowNoId.setKey("key new plus"); rowNoId.setValue("value now plus"); - List> modifications = prismContext.deltaFor(LookupTableType.class) + List> modifications = prismContext.deltaFor(LookupTableType.class) .item(F_ROW).replace(rowNoId) .asItemDeltas(); @@ -373,18 +371,19 @@ private PrismObject getTableFull(String tableOid, OperationResu private PrismObject getTablePlain(String tableOid, OperationResult result) throws ObjectNotFoundException, SchemaException { - return repositoryService.getObject(LookupTableType.class, tableOid,null, result); + return repositoryService.getObject(LookupTableType.class, tableOid, null, result); } - protected void executeAndCheckModification(List> modifications, OperationResult result, int versionDelta, - List keysWithGeneratedTimestamps) - throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, IOException { + protected void executeAndCheckModification(List> modifications, + OperationResult result, int versionDelta, List keysWithGeneratedTimestamps) + throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { executeAndCheckModification(modifications, result, versionDelta, keysWithGeneratedTimestamps, null); } - protected void executeAndCheckModification(List> modifications, OperationResult result, int versionDelta, - List keysWithGeneratedTimestamps, List replacedKeys) - throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, IOException { + protected void executeAndCheckModification( + List> modifications, OperationResult result, int versionDelta, + List keysWithGeneratedTimestamps, List replacedKeys) + throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { RepoModifyOptions modifyOptions = getModifyOptions(); if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions) && versionDelta == 0) { versionDelta = 1; @@ -398,9 +397,9 @@ protected void executeAndCheckModification(List> modifications, O } private void checkTable(String oid, OperationResult result, PrismObject expectedObject, - List> modifications, int expectedVersion, - List keysWithNewGeneratedTimestamps, List replacedKeys) - throws SchemaException, ObjectNotFoundException, IOException { + List> modifications, int expectedVersion, + List keysWithNewGeneratedTimestamps, List replacedKeys) + throws SchemaException, ObjectNotFoundException { expectedObject.setOid(oid); // remove keys that will be replaced @@ -413,9 +412,9 @@ private void checkTable(String oid, OperationResult result, PrismObject actualObject = getFullTable(oid, result); - LOGGER.trace("Actual object from repo = \n{}", actualObject.debugDump()); + logger.trace("Actual object from repo = \n{}", actualObject.debugDump()); // before comparison, check and remove generated timestamps if (keysWithNewGeneratedTimestamps != null) { @@ -456,9 +455,10 @@ private LookupTableRowType findRow(PrismObject table, String ke } } - private PrismObject getFullTable(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException { - SelectorOptions retrieve = SelectorOptions.create(prismContext.toUniformPath(F_ROW), GetOperationOptions.createRetrieve(INCLUDE)); + private PrismObject getFullTable(String oid, OperationResult result) + throws ObjectNotFoundException, SchemaException { + SelectorOptions retrieve = SelectorOptions.create( + prismContext.toUniformPath(F_ROW), GetOperationOptions.createRetrieve(INCLUDE)); return repositoryService.getObject(LookupTableType.class, oid, Arrays.asList(retrieve), result); } - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyAssignmentTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyAssignmentTest.java index 70c016de7a1..fe6ea83d743 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyAssignmentTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyAssignmentTest.java @@ -10,8 +10,6 @@ import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; -import static com.evolveum.midpoint.prism.util.PrismTestUtil.resetPrismContext; - import java.io.File; import java.util.List; @@ -20,14 +18,12 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -53,14 +49,10 @@ public class ModifyAssignmentTest extends BaseSQLRepoTest { private static final String ROLE_A1_OID = "aaaa00aa-aa00-aa00-a0a0-000000000001"; private static final String ROLE_A2_OID = "aaaa00aa-aa00-aa00-a0a0-000000000002"; - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - resetPrismContext(MidPointPrismContextFactory.FACTORY); + @Override + public void initSystem() throws Exception { //given //no role - PrismObject role = prismContext.parseObject(FILE_ROLE); OperationResult result = new OperationResult("add role"); @@ -352,7 +344,7 @@ public void test040RenameAssignmentToInducement() throws Exception { @Test public void test100AssignmentAdd() throws Exception { //given - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject roleBefore = getObject(RoleType.class, ROLE_OID); display("Role before", roleBefore); @@ -387,7 +379,7 @@ public void test100AssignmentAdd() throws Exception { @Test public void test110AssignmentAddDeleteIds() throws Exception { //given - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject roleBefore = getObject(RoleType.class, ROLE_OID); display("Role before", roleBefore); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTest.java index b25246e5a49..8cc7dc14625 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2019 Evolveum and contributors + * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. @@ -7,45 +7,28 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.prism.SerializationOptions.createSerializeForExport; import static com.evolveum.midpoint.schema.GetOperationOptions.createRawCollection; import static com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationExecutionStatusType.COMPLETED; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.fail; import java.io.File; -import java.io.IOException; import java.sql.Timestamp; import java.util.*; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import com.evolveum.prism.xml.ns._public.types_3.PolyStringLangType; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import org.hibernate.Session; import org.jetbrains.annotations.NotNull; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; -import org.xml.sax.SAXException; import com.evolveum.midpoint.common.SynchronizationUtils; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.ItemDeltaCollectionsUtil; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.PropertyDelta; -import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; @@ -61,27 +44,29 @@ import com.evolveum.midpoint.repo.sql.data.common.RObject; import com.evolveum.midpoint.repo.sql.testing.SqlRepoTestUtil; import com.evolveum.midpoint.schema.DeltaConvertor; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.internals.InternalsConfig; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType; +import com.evolveum.prism.xml.ns._public.types_3.PolyStringLangType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; +import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * @author lazyman */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ModifyTest extends BaseSQLRepoTest { @@ -97,17 +82,6 @@ public class ModifyTest extends BaseSQLRepoTest { private static final File SYSTEM_CONFIGURATION_BEFORE_FILE = new File(TEST_DIR, "system-configuration-before.xml"); private static final File SYSTEM_CONFIGURATION_AFTER_FILE = new File(TEST_DIR, "system-configuration-after.xml"); - @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { - PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - - @BeforeClass - public void setupClass() { - InternalsConfig.encryptionChecks = false; - } - @Override public void initSystem() throws Exception { super.initSystem(); @@ -115,6 +89,7 @@ public void initSystem() throws Exception { // This is an experimental feature, so it needs to be explicitly enabled. This will be eliminated later, // when we make it enabled by default. sqlRepositoryService.getConfiguration().setEnableIndexOnlyItems(true); + InternalsConfig.encryptionChecks = false; } protected RepoModifyOptions getModifyOptions() { @@ -194,7 +169,7 @@ public void test030ModifyUserOnNonExistingAccountTest() throws Exception { @Test public void test031ModifyUserOnExistingAccountTest() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); //add account PrismObject account = prismContext.parseObject(ACCOUNT_FILE); @@ -230,7 +205,7 @@ public void test031ModifyUserOnExistingAccountTest() throws Exception { @Test public void test032ModifyTaskObjectRef() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); File taskFile = new File(TEST_DIR, "task.xml"); System.out.println("ADD"); PrismObject task = prismContext.parseObject(taskFile); @@ -319,7 +294,7 @@ private void checkReference(String taskOid) { @Test // MID-4801 (this passed even before fixing that issue) public void test035ModifyTaskOwnerRef() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); TaskType task = new TaskType(prismContext) .oid("035") .name("task035") @@ -338,7 +313,7 @@ public void test035ModifyTaskOwnerRef() throws Exception { @Test // MID-4801 (this failed before fixing that issue) public void test036ModifyTaskOwnerRefAddAndDelete() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); TaskType task = new TaskType(prismContext) .oid("036") .name("task036") @@ -350,8 +325,8 @@ public void test036ModifyTaskOwnerRefAddAndDelete() throws Exception { List> modifications = prismContext.deltaFor(TaskType.class) .item(TaskType.F_OWNER_REF) - .add(ObjectTypeUtil.createObjectRef("owner-new", ObjectTypes.USER)) - .delete(ObjectTypeUtil.createObjectRef("owner-old", ObjectTypes.USER)) + .add(ObjectTypeUtil.createObjectRef("owner-new", ObjectTypes.USER)) + .delete(ObjectTypeUtil.createObjectRef("owner-old", ObjectTypes.USER)) .asItemDeltas(); repositoryService.modifyObject(TaskType.class, task.getOid(), modifications, getModifyOptions(), result); assertTaskOwner(task.getOid(), "owner-new"); @@ -359,7 +334,7 @@ public void test036ModifyTaskOwnerRefAddAndDelete() throws Exception { @Test // MID-4801 public void test050ModifyUserEmployeeNumber() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); UserType user = new UserType(prismContext) .oid("050") .name("user050") @@ -370,8 +345,8 @@ public void test050ModifyUserEmployeeNumber() throws Exception { List> modifications = prismContext.deltaFor(UserType.class) .item(UserType.F_EMPLOYEE_NUMBER) - .add("new") - .delete("old") + .add("new") + .delete("old") .asItemDeltas(); repositoryService.modifyObject(UserType.class, user.getOid(), modifications, getModifyOptions(), result); assertUserEmployeeNumber(user.getOid(), "new"); @@ -379,7 +354,7 @@ public void test050ModifyUserEmployeeNumber() throws Exception { @Test // MID-4801 public void test055DeleteUserEmployeeNumberWrong() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); UserType user = new UserType(prismContext) .oid("055") .name("user055") @@ -390,7 +365,7 @@ public void test055DeleteUserEmployeeNumberWrong() throws Exception { List> modifications = prismContext.deltaFor(UserType.class) .item(UserType.F_EMPLOYEE_NUMBER) - .delete("oldWrong") + .delete("oldWrong") .asItemDeltas(); repositoryService.modifyObject(UserType.class, user.getOid(), modifications, getModifyOptions(), result); @@ -403,7 +378,7 @@ public void test055DeleteUserEmployeeNumberWrong() throws Exception { @Test // MID-4801 public void test056EmptyUserEmployeeNumberDelta() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); UserType user = new UserType(prismContext) .oid("056") .name("user056") @@ -469,7 +444,6 @@ public void test100ModifyUserAddRole() throws Exception { ObjectModificationType modification = PrismTestUtil.parseAtomicValue(new File(TEST_DIR + "/modify-user-add-roles.xml"), ObjectModificationType.COMPLEX_TYPE); - ObjectDelta delta = DeltaConvertor.createObjectDelta(modification, UserType.class, prismContext); repositoryService.modifyObject(UserType.class, userToModifyOid, delta.getModifications(), getModifyOptions(), parentResult); @@ -492,7 +466,7 @@ public void test100ModifyUserAddRole() throws Exception { @Test public void test120ModifyAccountMetadata() throws Exception { // GIVEN - OperationResult parentResult = createResult(); + OperationResult parentResult = createOperationResult(); repositoryService.deleteObject(ShadowType.class, "1234567890", parentResult); // from earlier test @@ -526,7 +500,6 @@ public void test120ModifyAccountMetadata() throws Exception { String oid = repositoryService.addObject(shadowBefore, null, parentResult); - // WHEN when(); @@ -652,7 +625,6 @@ public void test140ModifyAccountSynchronizationSituation() throws Exception { SynchronizationSituationDescriptionType description = afterFirstModifyType.getSynchronizationSituationDescription().get(0); assertEquals(SynchronizationSituationType.LINKED, description.getSituation()); - timestamp = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis()); syncSituationDeltas = SynchronizationUtils.createSynchronizationSituationAndDescriptionDelta(afterFirstModify, null, null, false, timestamp, prismContext); @@ -683,7 +655,7 @@ public void test140ModifyAccountSynchronizationSituation() throws Exception { @Test public void test142ModifyAccountAttributeSameValue() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject account = prismContext.parseObject(ACCOUNT_ATTRIBUTE_FILE); repositoryService.addObject(account, null, result); @@ -706,7 +678,7 @@ public void test142ModifyAccountAttributeSameValue() throws Exception { @Test public void test144ModifyAccountAttributeDifferent() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); assertNotNull("account-attribute was not imported in previous tests", accountOid); @@ -727,7 +699,7 @@ public void test144ModifyAccountAttributeDifferent() throws Exception { @Test public void test148ModifyAssignmentExtension() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.parseObject(new File(TEST_DIR, "user-with-assignment-extension.xml")); repositoryService.addObject(user, null, result); @@ -751,7 +723,7 @@ public void test148ModifyAssignmentExtension() throws Exception { @Test public void test150ModifyRoleAddInducements() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); File roleFile = new File(TEST_DIR, "role-modify.xml"); //add first user @@ -799,11 +771,13 @@ public void test150ModifyRoleAddInducements() throws Exception { @Test public void test160ModifyWithPrecondition() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // GIVEN String versionBefore = repositoryService.getVersion(RoleType.class, roleOid, result); - ModificationPrecondition precondition = o -> { throw new PreconditionViolationException("hello"); }; + ModificationPrecondition precondition = o -> { + throw new PreconditionViolationException("hello"); + }; // WHEN List> itemDeltas = prismContext.deltaFor(RoleType.class) @@ -823,7 +797,7 @@ public void test160ModifyWithPrecondition() throws Exception { @Test public void test162ModifyWithPrecondition2() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // GIVEN String versionBefore = repositoryService.getVersion(RoleType.class, roleOid, result); @@ -848,7 +822,7 @@ public void test162ModifyWithPrecondition2() throws Exception { @Test public void test164ModifyWithVersionPreconditionFalse() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // GIVEN String versionBefore = repositoryService.getVersion(RoleType.class, roleOid, result); @@ -873,7 +847,7 @@ public void test164ModifyWithVersionPreconditionFalse() throws Exception { @Test public void test166ModifyWithVersionPreconditionTrue() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // GIVEN String versionBefore = repositoryService.getVersion(RoleType.class, roleOid, result); @@ -886,14 +860,14 @@ public void test166ModifyWithVersionPreconditionTrue() throws Exception { repositoryService.modifyObject(RoleType.class, roleOid, itemDeltas, precondition, null, result); String versionAfter = repositoryService.getVersion(RoleType.class, roleOid, result); - assertEquals("unexpected version change", Integer.parseInt(versionBefore)+1, Integer.parseInt(versionAfter)); + assertEquals("unexpected version change", Integer.parseInt(versionBefore) + 1, Integer.parseInt(versionAfter)); String description = repositoryService.getObject(RoleType.class, roleOid, null, result).asObjectable().getDescription(); assertEquals("description was not set", "123456", description); } @Test public void test200ReplaceAttributes() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject account = prismContext.parseObject(ACCOUNT_ATTRIBUTE_FILE); account.setOid(null); @@ -979,9 +953,9 @@ private void assertAttribute(PrismObject shadow, String attrName private void assertAttribute(PrismObject shadow, QName attrQName, T... expectedValues) { PrismProperty attr = shadow.findProperty(ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName)); if (expectedValues.length == 0) { - assertTrue("Expected no value for attribute "+attrQName+" in "+shadow+", but it has "+attr, attr == null); + assertTrue("Expected no value for attribute " + attrQName + " in " + shadow + ", but it has " + attr, attr == null); } else { - assertNotNull("No attribute "+attrQName+" in "+shadow, attr); + assertNotNull("No attribute " + attrQName + " in " + shadow, attr); PrismAsserts.assertPropertyValue(attr, expectedValues); } } @@ -1040,7 +1014,7 @@ public void test210ModifyObjectCollection() throws Exception { @Test public void test250AddShadowPendingOperations() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject shadow = prismContext.createObjectable(ShadowType.class) .name("shadow1") @@ -1076,13 +1050,13 @@ public void test250AddShadowPendingOperations() throws Exception { @Test public void test260DeleteShadowPendingOperations() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject shadow = prismContext.createObjectable(ShadowType.class) .name("shadow2") .oid("000-aaa-bbb-ddd") .beginPendingOperation() - .executionStatus(COMPLETED) + .executionStatus(COMPLETED) .end() .asPrismObject(); repositoryService.addObject(shadow, null, result); @@ -1114,7 +1088,7 @@ public void test260DeleteShadowPendingOperations() throws Exception { @Test public void test300AddCaseWorkItem() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject caseObject = prismContext.createObjectable(CaseType.class) .name("testcase1") @@ -1147,7 +1121,7 @@ public void test300AddCaseWorkItem() throws Exception { @Test public void test310ModifyCaseWorkItemAssignee() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); final String OLD_OID = "0f4082cf-c0b6-4cd2-a3db-544c668bab0c"; final String NEW_OID = "4cbdc40b-5693-4174-8634-acd3e0b96168"; @@ -1157,8 +1131,8 @@ public void test310ModifyCaseWorkItemAssignee() throws Exception { .oid("7d0c37f8-26e5-4213-af95-cfde175f3ff7") .state("open") .beginWorkItem() - .id(1L) - .assigneeRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) + .id(1L) + .assigneeRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) .end() .asPrismObject(); repositoryService.addObject(caseObject, null, result); @@ -1167,7 +1141,7 @@ public void test310ModifyCaseWorkItemAssignee() throws Exception { List> itemDeltas = prismContext.deltaFor(CaseType.class) .item(CaseType.F_WORK_ITEM, 1L, CaseWorkItemType.F_ASSIGNEE_REF) - .replace(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) + .replace(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) .asItemDeltas(); repositoryService.modifyObject(CaseType.class, caseObject.getOid(), itemDeltas, getModifyOptions(), result); @@ -1182,7 +1156,7 @@ public void test310ModifyCaseWorkItemAssignee() throws Exception { @Test public void test320ModifyCaseWorkItemAssigneeAndCandidate() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); final String OLD_OID = "d886a44c-732d-44d4-8403-e7c44bbfba8b"; final String OLD2_OID = "9a28119e-1283-4328-9e2f-ef383728a4d1"; @@ -1192,10 +1166,10 @@ public void test320ModifyCaseWorkItemAssigneeAndCandidate() throws Exception { .name("case320") .state("open") .beginWorkItem() - .id(1L) - .assigneeRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) - .candidateRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) // intentionally the same - .candidateRef(new ObjectReferenceType().oid(OLD2_OID).type(UserType.COMPLEX_TYPE)) + .id(1L) + .assigneeRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) + .candidateRef(new ObjectReferenceType().oid(OLD_OID).type(UserType.COMPLEX_TYPE)) // intentionally the same + .candidateRef(new ObjectReferenceType().oid(OLD2_OID).type(UserType.COMPLEX_TYPE)) .end() .asPrismObject(); repositoryService.addObject(caseObject, null, result); @@ -1208,9 +1182,9 @@ public void test320ModifyCaseWorkItemAssigneeAndCandidate() throws Exception { List> itemDeltas = prismContext.deltaFor(CaseType.class) .item(CaseType.F_WORK_ITEM, 1L, CaseWorkItemType.F_ASSIGNEE_REF) - .replace(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) + .replace(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) .item(CaseType.F_WORK_ITEM, 1L, CaseWorkItemType.F_CANDIDATE_REF) - .add(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) + .add(new ObjectReferenceType().oid(NEW_OID).type(UserType.COMPLEX_TYPE)) .asItemDeltas(); repositoryService.modifyObject(CaseType.class, caseObject.getOid(), itemDeltas, getModifyOptions(), result); @@ -1250,14 +1224,14 @@ private List assertCandidate(String candidateOid, int expected @Test // MID-5104 public void test350ReplaceAssignmentModifyApprover() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.createObjectable(UserType.class) .name("test350") .oid("oid-350") .beginAssignment() - .id(123L) - .targetRef("oid0", RoleType.COMPLEX_TYPE) + .id(123L) + .targetRef("oid0", RoleType.COMPLEX_TYPE) .end() .asPrismObject(); repositoryService.addObject(user, null, result); @@ -1278,7 +1252,7 @@ public void test350ReplaceAssignmentModifyApprover() throws Exception { @Test // MID-5105 public void test360ReplaceModifyApprovers() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.createObjectable(UserType.class) .name("test360") @@ -1327,7 +1301,7 @@ public void test400RemoveCoreProtectedStringValueInMemory() throws Exception { .end() .end(); - PrismTestUtil.display("jack before", jack.asPrismObject()); + display("jack before", jack.asPrismObject()); ObjectDelta delta = prismContext.deltaFor(UserType.class) .item(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE) @@ -1336,7 +1310,7 @@ public void test400RemoveCoreProtectedStringValueInMemory() throws Exception { delta.applyTo(jack.asPrismObject()); - PrismTestUtil.display("jack after", jack.asPrismObject()); + display("jack after", jack.asPrismObject()); jack.asPrismObject().checkConsistence(); } @@ -1352,7 +1326,7 @@ public void test410RemoveExtensionProtectedStringValueInMemory() throws Exceptio protectedProperty.setRealValue(protectedValue.clone()); jack.asPrismObject().addExtensionItem(protectedProperty); - PrismTestUtil.display("jack before", jack.asPrismObject()); + display("jack before", jack.asPrismObject()); ObjectDelta delta = prismContext.deltaFor(UserType.class) .item(UserType.F_EXTENSION, "protected") @@ -1361,7 +1335,7 @@ public void test410RemoveExtensionProtectedStringValueInMemory() throws Exceptio delta.applyTo(jack.asPrismObject()); - PrismTestUtil.display("jack after", jack.asPrismObject()); + display("jack after", jack.asPrismObject()); jack.asPrismObject().checkConsistence(); } @@ -1369,7 +1343,7 @@ public void test410RemoveExtensionProtectedStringValueInMemory() throws Exceptio @Test // MID-5516 public void test420RemoveExtensionProtectedStringValueInRepo() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); ProtectedStringType protectedValue = protector.encryptString("hi"); UserType jack = new UserType(prismContext) @@ -1382,7 +1356,7 @@ public void test420RemoveExtensionProtectedStringValueInRepo() throws Exception repositoryService.addObject(jack.asPrismObject(), null, result); - PrismTestUtil.display("jack before", jack.asPrismObject()); + display("jack before", jack.asPrismObject()); // WHEN @@ -1397,7 +1371,7 @@ public void test420RemoveExtensionProtectedStringValueInRepo() throws Exception PrismObject jackAfter = repositoryService.getObject(UserType.class, jack.getOid(), null, result); - PrismTestUtil.display("jack after", jackAfter); + display("jack after", jackAfter); jackAfter.checkConsistence(); } @@ -1405,7 +1379,7 @@ public void test420RemoveExtensionProtectedStringValueInRepo() throws Exception @Test // MID-5826 - fortunately, in 4.0 this works due to reworked handling of extension values in repo public void test450ReplaceExtensionItem() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.createObjectable(UserType.class) .name("test400") @@ -1444,7 +1418,7 @@ private void assertExtensionDateValue(String objectOid, int expected) { @Test(enabled = false) // MID-5958 public void test500ReferenceTargetNameAdding() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PolyStringType parentName = new PolyStringType("Parent"); parentName.setNorm("Parent"); @@ -1481,7 +1455,7 @@ public void test500ReferenceTargetNameAdding() throws Exception { @Test public void test510ModifySystemConfiguration() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject before = prismContext.parseObject(SYSTEM_CONFIGURATION_BEFORE_FILE); repositoryService.addObject(before, null, result); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTestReindex.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTestReindex.java index fdffc43c7db..41a7f322417 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTestReindex.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyTestReindex.java @@ -47,7 +47,7 @@ protected RepoModifyOptions getModifyOptions() { @Test public void testReindexExtensionItem() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.createObjectable(UserType.class) .name("unstable") @@ -74,7 +74,7 @@ public void testReindexExtensionItem() throws Exception { @Test // MID-5112 public void testReindexIndexOnlyItem() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); PrismObject user = prismContext.createObjectable(UserType.class) .name(getTestNameShort()) @@ -108,7 +108,7 @@ public void testReindexIndexOnlyItem() throws Exception { @Test // MID-5112 public void testReindexPhoto() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); byte[] PHOTO = new byte[] { 1, 2, 3, 4 }; @@ -130,7 +130,7 @@ public void testReindexPhoto() throws Exception { @Test // MID-5112 public void testReindexTaskResult() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); OperationResultType taskOperationResult = new OperationResultType().message("Hello there"); @@ -152,7 +152,7 @@ public void testReindexTaskResult() throws Exception { @Test // MID-5112 public void testReindexLookupTableRow() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); LookupTableRowType row = new LookupTableRowType(prismContext) .key("key") @@ -176,7 +176,7 @@ public void testReindexLookupTableRow() throws Exception { @Test // MID-5112 public void testReindexCertificationCampaignCase() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); AccessCertificationCaseType aCase = new AccessCertificationCaseType(prismContext) .stageNumber(1); @@ -203,7 +203,7 @@ public void testReindexCertificationCampaignCase() throws Exception { */ @Test public void testReindexShadow() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); String APPROVER_OID = "9123090439201432"; PrismObject shadow = prismContext.createObjectable(ShadowType.class) diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyUser.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyUser.java index a4e2d55862f..d4011284e6b 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyUser.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ModifyUser.java @@ -13,7 +13,6 @@ import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.DeltaConvertor; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; @@ -24,7 +23,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; @@ -44,13 +42,6 @@ public class ModifyUser extends BaseSQLRepoTest { private String userBigOid; private String shadowOid; - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - @Test public void test010Add() throws Exception { PrismObject user = PrismTestUtil.parseObject(new File(FOLDER_BASIC, "user.xml")); @@ -65,7 +56,7 @@ public void test010Add() throws Exception { @Test public void test020ModifyUser() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); ObjectModificationType modification = PrismTestUtil.parseAtomicValue( new File(FOLDER_BASIC, "t002.xml"), ObjectModificationType.COMPLEX_TYPE); @@ -89,7 +80,7 @@ public void test020ModifyUser() throws Exception { @Test public void test021ModifyUserNoEmpNum() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); ObjectModificationType modification = PrismTestUtil.parseAtomicValue( new File(FOLDER_BASIC, "t002a.xml"), ObjectModificationType.COMPLEX_TYPE); @@ -113,7 +104,7 @@ public void test021ModifyUserNoEmpNum() throws Exception { @Test public void test022ModifyUserEmptyEmpNum() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); ObjectModificationType modification = PrismTestUtil.parseAtomicValue( new File(FOLDER_BASIC, "t002b.xml"), ObjectModificationType.COMPLEX_TYPE); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ObjectDeltaUpdaterTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ObjectDeltaUpdaterTest.java index cb22629363f..87aa76e72c8 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ObjectDeltaUpdaterTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ObjectDeltaUpdaterTest.java @@ -24,8 +24,6 @@ import com.evolveum.midpoint.repo.sql.testing.TestStatementInspector; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.hibernate.Session; @@ -51,8 +49,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ObjectDeltaUpdaterTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(ObjectDeltaUpdaterTest.class); - private static final File DATA_FOLDER = new File("./src/test/resources/update"); private static final String FILE_USER = "user.xml"; @@ -1127,7 +1123,7 @@ public void test280AddPhoto() throws Exception { AssertJUnit.assertEquals(6, TestStatementInspector.getQueryCount()); } - LOGGER.info("test280AddPhoto check"); + logger.info("test280AddPhoto check"); try (Session session = factory.openSession()) { RUser u = session.get(RUser.class, userOid); @@ -1154,7 +1150,7 @@ public void test290ReplacePhoto() throws Exception { AssertJUnit.assertEquals(6, TestStatementInspector.getQueryCount()); } - LOGGER.info("test290ReplacePhoto check"); + logger.info("test290ReplacePhoto check"); try (Session session = factory.openSession()) { RUser u = session.get(RUser.class, userOid); @@ -1181,7 +1177,7 @@ public void test300DeletePhoto() throws Exception { AssertJUnit.assertEquals(5, TestStatementInspector.getQueryCount()); } - LOGGER.info("test300DeletePhoto check"); + logger.info("test300DeletePhoto check"); try (Session session = factory.openSession()) { RUser u = session.get(RUser.class, userOid); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/OrgStructTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/OrgStructTest.java index 0eed48ec6b6..5497bac4e04 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/OrgStructTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/OrgStructTest.java @@ -7,9 +7,27 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.FetchMode; +import org.hibernate.Session; +import org.hibernate.criterion.Restrictions; +import org.hibernate.query.Query; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.query.*; +import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.sql.data.common.ROrgClosure; @@ -17,7 +35,6 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; @@ -28,24 +45,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.hibernate.Criteria; -import org.hibernate.FetchMode; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.criterion.Restrictions; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import static org.testng.AssertJUnit.assertEquals; - @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class OrgStructTest extends BaseSQLRepoTest { @@ -90,8 +89,6 @@ public class OrgStructTest extends BaseSQLRepoTest { private static final String MODIFY_USER_DELETE_REF_OID = "00000000-8888-6666-0000-100000000002"; - private static final Trace LOGGER = TraceManager.getTrace(OrgStructTest.class); - private String elaineOid; private static final String ELAINE_NAME = "elaine"; private static final String ELAINE_NAME1 = "elaine1"; @@ -155,7 +152,7 @@ private void assertCount(Query query, int count) { /** * Tests for repo.matchObject() method */ - private void testMonkeySubordinate() throws SchemaException, ObjectNotFoundException { + private void testMonkeySubordinate() throws SchemaException { assertSubordinate(false, ORG_F003_OID, ORG_F001_OID); assertSubordinate(true, ORG_F003_OID, ORG_F003_OID); assertSubordinate(true, ORG_F003_OID, ORG_F005_OID); @@ -211,13 +208,13 @@ private void testMonkeySubordinate() throws SchemaException, ObjectNotFoundExcep private void assertSubordinate(boolean expected, String upperOrgOid, String... lowerObjectOids) throws SchemaException { Collection lowerObjectOidCol = Arrays.asList(lowerObjectOids); - LOGGER.debug("=======> {}: {}", upperOrgOid, lowerObjectOidCol); + logger.debug("=======> {}: {}", upperOrgOid, lowerObjectOidCol); boolean actual = repositoryService.isAnySubordinate(upperOrgOid, lowerObjectOidCol); if (expected != actual) { - LOGGER.error("=======X {}: {}; expected={}, actual={}", new Object[]{upperOrgOid, lowerObjectOidCol, expected, actual}); + logger.error("=======X {}: {}; expected={}, actual={}", new Object[]{upperOrgOid, lowerObjectOidCol, expected, actual}); assertEquals("Wrong subordinate match: " + upperOrgOid + " to " + lowerObjectOidCol, expected, actual); } else { - LOGGER.debug("=======O {}: {}; got={}", new Object[]{upperOrgOid, lowerObjectOidCol, expected}); + logger.debug("=======O {}: {}; got={}", new Object[]{upperOrgOid, lowerObjectOidCol, expected}); } } @@ -236,7 +233,7 @@ public void test001addOrgStructObjectsIncorrect() throws Exception { Session session = open(); try { - LOGGER.info("==============CLOSURE TABLE=========="); + logger.info("==============CLOSURE TABLE=========="); // descendants of F007 - F007<0>, F009<1>, F008<2>, F0010<2> Criteria criteria = session.createCriteria(ROrgClosure.class) .createCriteria("ancestor", "anc") @@ -245,7 +242,7 @@ public void test001addOrgStructObjectsIncorrect() throws Exception { List orgClosure = criteria.list(); for (ROrgClosure c : orgClosure) { - LOGGER.info("{}", c.getDescendant()); + logger.info("{}", c.getDescendant()); } AssertJUnit.assertEquals(4, orgClosure.size()); @@ -265,7 +262,7 @@ public void test001addOrgStructObjectsIncorrect() throws Exception { AssertJUnit.assertNotNull(users); AssertJUnit.assertEquals(1, users.size()); UserType elaine1 = users.get(0).asObjectable(); - LOGGER.info("--->elaine1<----"); + logger.info("--->elaine1<----"); AssertJUnit.assertEquals("Expected name elaine1, but got " + elaine1.getName().getOrig(), "elaine1", elaine1.getName().getOrig()); AssertJUnit.assertEquals("Expected elaine has one org ref, but got " + elaine1.getParentOrgRef().size(), 2, elaine1.getParentOrgRef().size()); @@ -291,9 +288,9 @@ public void test002modifyOrgStructAddRef() throws Exception { try { orgClosure = getOrgClosureByDescendant(MODIFY_ORG_ADD_REF_OID, session); - LOGGER.info("before modify"); + logger.info("before modify"); for (ROrgClosure c : orgClosure) { - LOGGER.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); + logger.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); } AssertJUnit.assertEquals(3, orgClosure.size()); } finally { @@ -306,9 +303,9 @@ public void test002modifyOrgStructAddRef() throws Exception { try { orgClosure = getOrgClosureByDescendant(MODIFY_ORG_ADD_REF_OID, session); - LOGGER.info("after modify"); + logger.info("after modify"); for (ROrgClosure c : orgClosure) { - LOGGER.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); + logger.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); } AssertJUnit.assertEquals(4, orgClosure.size()); @@ -320,7 +317,7 @@ public void test002modifyOrgStructAddRef() throws Exception { for (String ancestorOid : ancestors) { orgClosure = getOrgClosure(ancestorOid, MODIFY_ORG_ADD_REF_OID, session); - LOGGER.info("=> A: {}, D: {}", orgClosure.get(0).getAncestor(), orgClosure.get(0).getDescendant()); + logger.info("=> A: {}, D: {}", orgClosure.get(0).getAncestor(), orgClosure.get(0).getDescendant()); AssertJUnit.assertEquals(1, orgClosure.size()); AssertJUnit.assertEquals(ancestorOid, orgClosure.get(0).getAncestor().getOid()); @@ -360,9 +357,9 @@ public void test002modifyOrgStructAddRefIncorrect() throws Exception { try { List orgClosure = getOrgClosureByDescendant(MODIFY_ORG_INCORRECT_ADD_REF_OID, session); - LOGGER.info("after modify incorrect - closure"); + logger.info("after modify incorrect - closure"); for (ROrgClosure c : orgClosure) { - LOGGER.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); + logger.info("{}\t{}", new Object[]{c.getAncestor().getOid(), c.getDescendant().getOid()}); } AssertJUnit.assertEquals(5, orgClosure.size()); @@ -398,7 +395,7 @@ public void test003modifyOrgStructDeleteRef() throws Exception { Session session = open(); try { - LOGGER.info("==>before modify - delete<=="); + logger.info("==>before modify - delete<=="); List orgClosure = getOrgClosure(ORG_F003_OID, MODIFY_ORG_DELETE_REF_OID, session); AssertJUnit.assertEquals(1, orgClosure.size()); @@ -409,7 +406,7 @@ public void test003modifyOrgStructDeleteRef() throws Exception { session.clear(); session.beginTransaction(); - LOGGER.info("==>after modify - delete<=="); + logger.info("==>after modify - delete<=="); orgClosure = getOrgClosure(ORG_F003_OID, MODIFY_ORG_DELETE_REF_OID, session); AssertJUnit.assertEquals(0, orgClosure.size()); } finally { @@ -428,7 +425,7 @@ public void test003modifyOrgStructDeleteRefIncorrect() throws Exception { Session session = open(); try { - LOGGER.info("==>before modify - delete<=="); + logger.info("==>before modify - delete<=="); List orgClosure = getOrgClosure(ORG_F012_OID, MODIFY_ORG_INCORRECT_DELETE_REF_OID, session); AssertJUnit.assertEquals(0, orgClosure.size()); @@ -439,7 +436,7 @@ public void test003modifyOrgStructDeleteRefIncorrect() throws Exception { session.clear(); session.beginTransaction(); - LOGGER.info("==>after modify - delete<=="); + logger.info("==>after modify - delete<=="); orgClosure = getOrgClosure(ORG_F012_OID, MODIFY_ORG_INCORRECT_DELETE_REF_OID, session); AssertJUnit.assertEquals(0, orgClosure.size()); } finally { @@ -477,7 +474,7 @@ public void test006searchOrgStructUserUnbounded() throws Exception { List> orgClosure = repositoryService.searchObjects(ObjectType.class, objectQuery, null, parentResult); for (PrismObject u : orgClosure) { - LOGGER.info("USER000 ======> {}", ObjectTypeUtil.toShortString(u.asObjectable())); + logger.info("USER000 ======> {}", ObjectTypeUtil.toShortString(u.asObjectable())); } AssertJUnit.assertEquals(7, orgClosure.size()); @@ -491,9 +488,9 @@ public void test007searchOrgStructOrgDepth() throws Exception { try { List orgClosure = getOrgClosure(SEARCH_ORG_OID_DEPTH1, SEARCH_ORG_OID_DEPTH1, session); - LOGGER.info("==============CLOSURE TABLE=========="); + logger.info("==============CLOSURE TABLE=========="); for (ROrgClosure o : orgClosure) { - LOGGER.info("=> A: {}, D: {}", o.getAncestor(), o.getDescendant()); + logger.info("=> A: {}, D: {}", o.getAncestor(), o.getDescendant()); } AssertJUnit.assertEquals(1, orgClosure.size()); session.getTransaction().commit(); @@ -506,7 +503,7 @@ public void test007searchOrgStructOrgDepth() throws Exception { List> sOrgClosure = repositoryService.searchObjects(ObjectType.class, objectQuery, null, parentResult); for (PrismObject u : sOrgClosure) { - LOGGER.info("USER000 ======> {}", ObjectTypeUtil.toShortString(u.asObjectable())); + logger.info("USER000 ======> {}", ObjectTypeUtil.toShortString(u.asObjectable())); } AssertJUnit.assertEquals(4, sOrgClosure.size()); } finally { @@ -527,7 +524,7 @@ public void test008searchRootOrg() throws Exception { List> rootOrgs = repositoryService.searchObjects(OrgType.class, qSearch, null, parentResult); for (PrismObject ro : rootOrgs) { - LOGGER.info("ROOT ========= {}", ObjectTypeUtil.toShortString(ro.asObjectable())); + logger.info("ROOT ========= {}", ObjectTypeUtil.toShortString(ro.asObjectable())); } AssertJUnit.assertEquals(5, rootOrgs.size()); } @@ -545,9 +542,9 @@ public void test009modifyOrgStructRemoveUser() throws Exception { repositoryService.modifyObject(UserType.class, elaineOid, delta.getModifications(), opResult); UserType userElaine = repositoryService.getObject(UserType.class, elaineOid, null, opResult).asObjectable(); - LOGGER.trace("elaine's og refs"); + logger.trace("elaine's og refs"); for (ObjectReferenceType ort : userElaine.getParentOrgRef()) { - LOGGER.trace("{}", ort); + logger.trace("{}", ort); if (ort.getOid().equals(MODIFY_USER_DELETE_REF_OID)) { AssertJUnit.fail("expected that elain does not have reference on the org with oid:" + MODIFY_USER_DELETE_REF_OID); } @@ -556,7 +553,7 @@ public void test009modifyOrgStructRemoveUser() throws Exception { @Test public void test011OrgFilter() throws Exception { - OperationResult opResult = createResult(); + OperationResult opResult = createOperationResult(); ObjectQuery query = prismContext.queryFor(ObjectType.class) .isDirectChildOf(ORG_F001_OID) @@ -572,7 +569,7 @@ public void test011OrgFilter() throws Exception { @Test public void test100ParentOrgRefFilterNullRelation() throws Exception { - OperationResult opResult = createResult(); + OperationResult opResult = createOperationResult(); ObjectQuery query = prismContext.queryFor(ObjectType.class) .item(ObjectType.F_PARENT_ORG_REF).ref(itemFactory().createReferenceValue(ORG_F001_OID)) @@ -587,7 +584,7 @@ public void test100ParentOrgRefFilterNullRelation() throws Exception { @Test public void test101ParentOrgRefFilterManagerRelation() throws Exception { - OperationResult opResult = createResult(); + OperationResult opResult = createOperationResult(); PrismReferenceValue refVal = itemFactory().createReferenceValue(ORG_F001_OID); refVal.setRelation(SchemaConstants.ORG_MANAGER); @@ -604,7 +601,7 @@ public void test101ParentOrgRefFilterManagerRelation() throws Exception { @Test public void test102ParentOrgRefFilterAnyRelation() throws Exception { - OperationResult opResult = createResult(); + OperationResult opResult = createOperationResult(); PrismReferenceValue refVal = itemFactory().createReferenceValue(ORG_F001_OID); refVal.setRelation(PrismConstants.Q_ANY); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/PerformanceTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/PerformanceTest.java index 93684ab4b37..e0e27e49b48 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/PerformanceTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/PerformanceTest.java @@ -12,8 +12,6 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.apache.commons.io.FileUtils; @@ -34,8 +32,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class PerformanceTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(PerformanceTest.class); - private static final String[] GIVEN_NAMES = {"James", "Josephine", "Art", "Lenna", "Donette", "Simona", "Mitsue", "Leota", "Sage", "Kris", "Minna", "Abel", "Kiley", "Graciela", "Cammy", "Mattie", "Meaghan", "Gladys", "Yuki", "Fletcher", "Bette", "Veronika", "Willard", "Maryann", "Alisha", "Allene", "Chanel", "Ezekiel", "Willow", @@ -76,14 +72,13 @@ public void test100Parsing() throws Exception { prismContext.serializerFor(lang).serialize(o); } } - LOGGER.info("xxx>> time: {}", (System.currentTimeMillis() - time)); + logger.info("xxx>> time: {}", (System.currentTimeMillis() - time)); } @Test(enabled = false) public void test200PrepareBigXml() throws Exception { File file = new File("./target/big-test.xml"); - Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); - try { + try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { writeHeader(writer); OrgType root = createOrgType("University", "University org. structure", "UROOT", "Bratislava", null); @@ -119,8 +114,6 @@ public void test200PrepareBigXml() throws Exception { } writeFooter(writer); - } finally { - writer.close(); } } @@ -136,11 +129,11 @@ public void test300Get() throws Exception { int COUNT = 100; for (int i = 0; i < COUNT; i++) { - LOGGER.info("Get operation {} of {}", i+1, COUNT); + logger.info("Get operation {} of {}", i+1, COUNT); repositoryService.getObject(UserType.class, oid, null, result); } long duration = System.currentTimeMillis() - time; - LOGGER.info("xxx>> time: {} ms, per get: {} ms", duration, (double) duration/COUNT); + logger.info("xxx>> time: {} ms, per get: {} ms", duration, (double) duration/COUNT); } @@ -180,12 +173,9 @@ private ShadowType createShadow(UserType user, String resourceOid, int resourceI } private String createUserName(String given, String family, int userId) { - StringBuilder sb = new StringBuilder(); - sb.append(given.toLowerCase().charAt(0)); - sb.append(family.toLowerCase().charAt(0)); - sb.append(StringUtils.leftPad(Integer.toString(userId), 8, "0")); - - return sb.toString(); + return String.valueOf(given.toLowerCase().charAt(0)) + + family.toLowerCase().charAt(0) + + StringUtils.leftPad(Integer.toString(userId), 8, "0"); } private UserType createUserType(int userId, String orgOid) throws SchemaException { diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java index 6afcecb2a79..8eea57a169a 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/QueryInterpreter2Test.java @@ -7,10 +7,48 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.prism.PrismConstants.T_ID; +import static com.evolveum.midpoint.prism.PrismConstants.T_PARENT; +import static com.evolveum.midpoint.prism.query.OrderDirection.ASCENDING; +import static com.evolveum.midpoint.prism.query.OrderDirection.DESCENDING; +import static com.evolveum.midpoint.schema.GetOperationOptions.createDistinct; +import static com.evolveum.midpoint.schema.SelectorOptions.createCollection; +import static com.evolveum.midpoint.util.QNameUtil.unqualify; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractWorkItemType.F_STAGE_NUMBER; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignStateType.IN_REVIEW_STAGE; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_OWNER_REF; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_STATE; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType.*; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationWorkItemType.*; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType.F_CONSTRUCTION; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType.F_RESOURCE_REF; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType.F_ASSIGNMENT; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType.F_CREATE_APPROVER_REF; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType.F_CREATOR_REF; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.*; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.TriggerType.F_TIMESTAMP; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.apache.commons.lang.StringUtils; +import org.hibernate.Session; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.*; -import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.repo.sql.data.common.any.RExtItem; @@ -22,74 +60,28 @@ import com.evolveum.midpoint.repo.sql.type.XMLGregorianCalendarType; import com.evolveum.midpoint.repo.sql.util.RUtil; import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.query_3.QueryType; -import org.apache.commons.lang.StringUtils; -import org.hibernate.Session; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; -import java.io.IOException; -import java.util.*; - -import static com.evolveum.midpoint.prism.PrismConstants.T_ID; -import static com.evolveum.midpoint.prism.PrismConstants.T_PARENT; -import static com.evolveum.midpoint.prism.query.OrderDirection.ASCENDING; -import static com.evolveum.midpoint.prism.query.OrderDirection.DESCENDING; -import static com.evolveum.midpoint.schema.GetOperationOptions.createDistinct; -import static com.evolveum.midpoint.schema.SelectorOptions.createCollection; -import static com.evolveum.midpoint.util.QNameUtil.unqualify; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractWorkItemType.F_STAGE_NUMBER; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignStateType.IN_REVIEW_STAGE; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_OWNER_REF; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType.F_STATE; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType.F_WORK_ITEM; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType.*; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationWorkItemType.*; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType.F_CONSTRUCTION; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType.F_RESOURCE_REF; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType.F_ASSIGNMENT; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType.F_CREATE_APPROVER_REF; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType.F_CREATOR_REF; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.*; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.TriggerType.F_TIMESTAMP; -import static org.testng.AssertJUnit.*; /** * @author lazyman * @author mederly */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class QueryInterpreter2Test extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(QueryInterpreter2Test.class); private static final File TEST_DIR = new File("./src/test/resources/query"); private static final QName FOO_QNAME = new QName("http://midpoint.evolveum.com/blabla", "foo"); @@ -103,12 +95,6 @@ public class QueryInterpreter2Test extends BaseSQLRepoTest { private static final QName ACTIVATION_STATUS_TYPE_QNAME = new QName(SchemaConstants.NS_C, ActivationStatusType.class.getSimpleName()); private static final QName SKIP_AUTOGENERATION_QNAME = new QName("http://example.com/p", "skipAutogeneration"); - @BeforeSuite - public void setup() throws SchemaException, SAXException, IOException { - PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - } - private RExtItem fooDefinition; private RExtItem shoeSizeDefinition; private RExtItem a1Definition; @@ -119,12 +105,8 @@ public void setup() throws SchemaException, SAXException, IOException { private RExtItem overrideActivationDefinition; private RExtItem skipAutogenerationDefinition; - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - + @Override + public void initSystem() throws Exception { List> objects = prismContext.parserFor( new File(FOLDER_BASIC, "objects.xml")).parseObjects(); OperationResult result = new OperationResult("add objects"); @@ -695,8 +677,8 @@ public void test0080QueryExistsAssignment() throws Exception { */ ObjectQuery query = prismContext.queryFor(UserType.class) .exists(F_ASSIGNMENT) - .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) - .eq(ActivationStatusType.ENABLED) + .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) + .eq(ActivationStatusType.ENABLED) .asc(F_NAME) .build(); @@ -723,8 +705,8 @@ public void test0081QueryExistsAssignmentWithRedundantBlock() throws Exception { ObjectQuery query = prismContext.queryFor(UserType.class) .block() .exists(F_ASSIGNMENT) - .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) - .eq(ActivationStatusType.ENABLED) + .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) + .eq(ActivationStatusType.ENABLED) .endBlock() .asc(F_NAME) .build(); @@ -752,10 +734,10 @@ public void test0082QueryExistsAssignmentWithRedundantBlock2() throws Exception ObjectQuery query = prismContext.queryFor(UserType.class) .block() .exists(F_ASSIGNMENT) - .block() - .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) - .eq(ActivationStatusType.ENABLED) - .endBlock() + .block() + .item(AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS) + .eq(ActivationStatusType.ENABLED) + .endBlock() .endBlock() .asc(F_NAME) .build(); @@ -783,7 +765,7 @@ public void test0084QueryExistsWithAnd() throws Exception { ObjectQuery query = prismContext.queryFor(ShadowType.class) .item(ShadowType.F_RESOURCE_REF).ref("111") .and() - .exists(ShadowType.F_PENDING_OPERATION) + .exists(ShadowType.F_PENDING_OPERATION) .build(); String real = getInterpretedQuery2(session, ShadowType.class, query); @@ -839,8 +821,8 @@ public void test0090QuerySingleAssignmentWithTargetAndTenant() throws Exception try { ObjectQuery query = prismContext.queryFor(UserType.class) .exists(F_ASSIGNMENT) - .item(AssignmentType.F_TARGET_REF).ref("target-oid-123") - .and().item(AssignmentType.F_TENANT_REF).ref("tenant-oid-456") + .item(AssignmentType.F_TARGET_REF).ref("target-oid-123") + .and().item(AssignmentType.F_TENANT_REF).ref("tenant-oid-456") .build(); String real = getInterpretedQuery2(session, UserType.class, query); @@ -896,7 +878,7 @@ public void test0092QueryAssignmentsWithTargetAndTenant() throws Exception { + " )\n"; assertEqualsIgnoreWhitespace(expected, real); } finally { - close(session); + close(session); } } @@ -1013,7 +995,6 @@ public void test0116QuerySubstringMultivalued() throws Exception { } } - @Test public void test0120QueryConnectorByType() throws Exception { Session session = open(); @@ -1411,8 +1392,8 @@ public void test0162QueryTriggerBeforeAfter() throws Exception { ObjectQuery query = prismContext.queryFor(ObjectType.class) .exists(ObjectType.F_TRIGGER) .block() - .item(F_TIMESTAMP).gt(lastScanTimestamp) - .and().item(F_TIMESTAMP).le(thisScanTimestamp) + .item(F_TIMESTAMP).gt(lastScanTimestamp) + .and().item(F_TIMESTAMP).le(thisScanTimestamp) .endBlock() .build(); String real = getInterpretedQuery2(session, ObjectType.class, query); @@ -1565,7 +1546,7 @@ public void test0200QueryTriggerTimestampDoubleWrong() throws Exception { .item(ObjectType.F_TRIGGER, F_TIMESTAMP).gt(thisScanTimestamp) .and().item(ObjectType.F_TRIGGER, F_TIMESTAMP).lt(thisScanTimestamp) .build(); - LOGGER.info(query.debugDump()); + logger.info(query.debugDump()); String real = getInterpretedQuery2(session, ObjectType.class, query); // correct translation but the filter is wrong: we need to point to THE SAME timestamp -> i.e. ForValue should be used here @@ -1677,7 +1658,7 @@ public void test0330InOidTest() throws Exception { } @Test - public void test0331InOidEmptyTest() throws Exception { + public void test0331InOidEmptyTest() { ObjectQuery query = prismContext.queryFor(ObjectType.class) .id(new String[0]).build(); query.setFilter(ObjectQueryUtil.simplify(query.getFilter(), prismContext)); @@ -1685,7 +1666,7 @@ public void test0331InOidEmptyTest() throws Exception { } @Test - public void test0332OwnerInOidEmptyTest() throws Exception { + public void test0332OwnerInOidEmptyTest() { ObjectQuery query = prismContext.queryFor(ObjectType.class) .ownerId(new String[0]).build(); query.setFilter(ObjectQueryUtil.simplify(query.getFilter(), prismContext)); @@ -1693,7 +1674,7 @@ public void test0332OwnerInOidEmptyTest() throws Exception { } @Test - public void test0333LongInOidEmptyTest() throws Exception { + public void test0333LongInOidEmptyTest() { ObjectQuery query = prismContext.queryFor(ObjectType.class) .id(new long[0]).build(); query.setFilter(ObjectQueryUtil.simplify(query.getFilter(), prismContext)); @@ -1701,7 +1682,7 @@ public void test0333LongInOidEmptyTest() throws Exception { } @Test - public void test0334LongOwnerInOidEmptyTest() throws Exception { + public void test0334LongOwnerInOidEmptyTest() { ObjectQuery query = prismContext.queryFor(ObjectType.class) .ownerId(new long[0]).build(); query.setFilter(ObjectQueryUtil.simplify(query.getFilter(), prismContext)); @@ -1921,7 +1902,6 @@ public void test0347QueryOrgTreeFindUsersRelationManager() throws Exception { } } - // MID-4337 @Test public void test0350QuerySubtreeDistinctCount() throws Exception { @@ -1976,37 +1956,6 @@ public void test0355QueryRoots() throws Exception { } } -// @Test -// public void asdf() throws Exception { -// Session session = open(); -// try { -// Criteria main = session.createCriteria(RUser.class, "u"); -// Criteria a = main.createCriteria("assignments", "a"); -// a.add(Restrictions.eq("a.assignmentOwner", RAssignmentOwner.FOCUS)); -// Criteria e = a.createCriteria("a.extension"); -// -// Criteria s = e.createCriteria("strings", "s"); -// -// Conjunction c2 = Restrictions.conjunction(); -// c2.add(Restrictions.eq("s.extensionType", RAssignmentExtensionType.EXTENSION)); -// c2.add(Restrictions.eq("s.name", new QName("http://midpoint.evolveum.com/blabla", "foo"))); -// c2.add(Restrictions.eq("s.value", "uid=jbond,ou=People,dc=example,dc=com")); -// -// Conjunction c1 = Restrictions.conjunction(); -// c1.add(Restrictions.eq("a.targetRef.targetOid", "1234")); -// c1.add(Restrictions.eq("a.targetRef.type", RObjectType.ORG)); -// -// main.add(Restrictions.and(c1, c2)); -// -// main.setProjection(Projections.property("u.fullObject")); -// -// String expected = HibernateToSqlTranslator.toSql(main); -// LOGGER.info(">>> >>> {}", expected); -// } finally { -// close(session); -// } -// } - @Test public void test0400ActivationQueryWrong() throws Exception { XMLGregorianCalendar thisScanTimestamp = XMLGregorianCalendarType.asXMLGregorianCalendar(new Date()); @@ -2053,10 +2002,10 @@ public void test0405ActivationQueryCorrect() throws Exception { .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) .or().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) .or().exists(F_ASSIGNMENT) - .block() - .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) - .or().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) - .endBlock() + .block() + .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) + .or().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) + .endBlock() .build(); Session session = open(); @@ -2091,20 +2040,20 @@ public void test0410ActivationQueryWrong() throws Exception { ObjectQuery query = prismContext.queryFor(FocusType.class) .block() - .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) - .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) + .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) + .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) .endBlock() .or().block() - .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) - .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) + .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) + .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) .endBlock() .or().block() - .item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) - .and().item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) + .item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) + .and().item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) .endBlock() .or().block() - .item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) - .and().item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) + .item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) + .and().item(F_ASSIGNMENT, AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) .endBlock() .build(); @@ -2154,22 +2103,22 @@ public void test0415ActivationQueryCorrect() throws Exception { ObjectQuery query = prismContext.queryFor(FocusType.class) .block() - .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) - .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) + .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) + .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) .endBlock() .or().block() - .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) - .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) + .item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) + .and().item(FocusType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) .endBlock() .or() - .exists(F_ASSIGNMENT) - .block() - .item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) - .and().item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) - .or() - .item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) - .and().item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) - .endBlock() + .exists(F_ASSIGNMENT) + .block() + .item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).gt(lastScanTimestamp) + .and().item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_FROM).le(thisScanTimestamp) + .or() + .item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).gt(lastScanTimestamp) + .and().item(AssignmentType.F_ACTIVATION, ActivationType.F_VALID_TO).le(thisScanTimestamp) + .endBlock() .build(); Session session = open(); @@ -2249,7 +2198,7 @@ public void test0500OrgQuery() throws Exception { private void checkQueryResult(Class type, String oid, OrgFilter.Scope scope, int count) throws Exception { - LOGGER.info("checkQueryResult"); + logger.info("checkQueryResult"); ObjectQuery query = prismContext.queryFor(type) .isInScopeOf(oid, scope) @@ -2259,7 +2208,7 @@ private void checkQueryResult(Class type, String oid, OperationResult result = new OperationResult("checkQueryResult"); List> objects = repositoryService.searchObjects(type, query, null, result); for (PrismObject object : objects) { - LOGGER.info("{}", object.getOid()); + logger.info("{}", object.getOid()); } int realCount = objects.size(); assertEquals("Expected count doesn't match for searchObjects " + query, count, realCount); @@ -2438,7 +2387,7 @@ public void test0570queryObjectypeByTypeUserAndLocality() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(UserType.class) - .item(UserType.F_LOCALITY).eqPoly("Caribbean", "caribbean") + .item(UserType.F_LOCALITY).eqPoly("Caribbean", "caribbean") .build(); String real = getInterpretedQuery2(session, ObjectType.class, query); @@ -2466,7 +2415,7 @@ public void test0570queryObjectypeByTypeUserAndLocality() throws Exception { * must be used for columns in "properties" parameter. */ private void checkQueryTypeAlias(String query, String table, String... properties) { - LOGGER.info("SQL generated = {}", query); + logger.info("SQL generated = {}", query); String[] array = query.split(" "); String alias = null; @@ -2494,7 +2443,7 @@ public void test0575QueryObjectypeByTypeOrgAndLocality() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(OrgType.class) - .item(OrgType.F_LOCALITY).eqPoly("Caribbean", "caribbean") + .item(OrgType.F_LOCALITY).eqPoly("Caribbean", "caribbean") .build(); String real = getInterpretedQuery2(session, ObjectType.class, query); @@ -2523,7 +2472,7 @@ public void test0580QueryObjectypeByTypeAndExtensionAttribute() throws Exception try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(UserType.class) - .item(UserType.F_EXTENSION, new QName("http://example.com/p", "weapon")).eq("some weapon name") + .item(UserType.F_EXTENSION, new QName("http://example.com/p", "weapon")).eq("some weapon name") .build(); RQueryImpl realQuery = (RQueryImpl) getInterpretedQuery2Whole(session, ObjectType.class, query, false, null); @@ -2551,7 +2500,7 @@ public void test0590QueryObjectypeByTypeAndReference() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(UserType.class) - .item(UserType.F_LINK_REF).ref("123") + .item(UserType.F_LINK_REF).ref("123") .build(); String real = getInterpretedQuery2(session, ObjectType.class, query); @@ -2581,13 +2530,13 @@ public void test0600QueryObjectypeByTypeComplex() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(UserType.class) - .block() - .item(UserType.F_LOCALITY).eqPoly("Caribbean", "caribbean") - .or().item(UserType.F_LOCALITY).eqPoly("Adriatic", "adriatic") - .endBlock() + .block() + .item(UserType.F_LOCALITY).eqPoly("Caribbean", "caribbean") + .or().item(UserType.F_LOCALITY).eqPoly("Adriatic", "adriatic") + .endBlock() .or().type(OrgType.class) .block() - .item(OrgType.F_ORG_TYPE).eq("functional") + .item(OrgType.F_ORG_TYPE).eq("functional") .endBlock() .or().type(ReportType.class) .build(); @@ -2656,7 +2605,7 @@ public void test0605QueryObjectypeByTypeAndReference() throws Exception { ObjectQuery query = prismContext.queryFor(ObjectType.class) .id("c0c010c0-d34d-b33f-f00d-111111111111") .or().type(RoleType.class) - .item(roleDef, RoleType.F_DELEGATED_REF).ref("c0c010c0-d34d-b33f-f00d-111111111111") + .item(roleDef, RoleType.F_DELEGATED_REF).ref("c0c010c0-d34d-b33f-f00d-111111111111") .build(); String real = getInterpretedQuery2(session, ObjectType.class, query); String expected = "select o.oid, o.fullObject\n" @@ -2680,7 +2629,7 @@ public void test0605QueryObjectypeByTypeAndReference() throws Exception { } } - @Test(enabled = false) + @Test(enabled = false) public void test0606QueryObjectypeByTypeAndOwnerRefOverloaded() throws Exception { Session session = open(); try { @@ -2753,7 +2702,7 @@ public void test0610QueryGenericClob() throws Exception { .build(); getInterpretedQuery2(session, GenericObjectType.class, query); } catch (QueryException ex) { - LOGGER.info("Exception", ex); + logger.info("Exception", ex); throw ex; } finally { close(session); @@ -2871,7 +2820,6 @@ public void test0630QueryGenericBoolean() throws Exception { public void test0640queryAssignmentExtensionBoolean() throws Exception { Session session = open(); try { - SchemaRegistry registry = prismContext.getSchemaRegistry(); PrismPropertyDefinition propDef = prismContext.definitionFactory().createPropertyDefinition( SKIP_AUTOGENERATION_QNAME, DOMUtil.XSD_BOOLEAN); @@ -3064,8 +3012,8 @@ public void test0715QueryWorkItemsForCase() throws Exception { ObjectQuery query = prismContext.queryFor(AccessCertificationWorkItemType.class) .exists(PrismConstants.T_PARENT) .block() - .id(1) - .and().ownerId("123456") + .id(1) + .and().ownerId("123456") .endBlock() .build(); String real = getInterpretedQuery2(session, AccessCertificationWorkItemType.class, query, false); @@ -3093,7 +3041,7 @@ public void test0717QueryWorkItemsForCampaign() throws Exception { try { ObjectQuery query = prismContext.queryFor(AccessCertificationWorkItemType.class) .exists(PrismConstants.T_PARENT) - .ownerId("campaignOid1") + .ownerId("campaignOid1") .build(); String real = getInterpretedQuery2(session, AccessCertificationWorkItemType.class, query, false); String expected = "select\n" @@ -3231,8 +3179,8 @@ public void test0740QueryCertCasesByCampaignOwner() throws Exception { ObjectQuery query = prismContext.queryFor(AccessCertificationCaseType.class) .exists(T_PARENT) .block() - .id(123456L) - .or().item(F_OWNER_REF).ref(ownerRef) + .id(123456L) + .or().item(F_OWNER_REF).ref(ownerRef) .endBlock() .build(); @@ -3533,7 +3481,6 @@ public void test0770CaseParentFilter() throws Exception { } } - @Test public void test0800OrderBySingleton() throws Exception { Session session = open(); @@ -3614,8 +3561,9 @@ public void test0820OrderByTargetName() throws Exception { } } - @Test(expectedExceptions = IllegalArgumentException.class) // should fail, as Equals supports single-value right side only - // TODO this should be perhaps checked in EqualFilter + @Test(expectedExceptions = IllegalArgumentException.class) + // should fail, as Equals supports single-value right side only + // TODO this should be perhaps checked in EqualFilter public void test0900EqualsMultivalue() throws Exception { Session session = open(); @@ -3671,7 +3619,8 @@ public void test0910PreferredLanguageEqualsCostCenter() throws Exception { } } - @Test(enabled = false) // different types of properties that are to be compared (polystring vs string in this case) are not supported yet + @Test(enabled = false) + // different types of properties that are to be compared (polystring vs string in this case) are not supported yet public void test0915OrganizationEqualsCostCenter() throws Exception { Session session = open(); @@ -3700,9 +3649,9 @@ public void test0920DecisionsNotAnswered() throws Exception { ObjectQuery query = prismContext.queryFor(AccessCertificationCaseType.class) .exists(F_WORK_ITEM) .block() - .item(F_ASSIGNEE_REF).ref("123456") - .and().item(F_STAGE_NUMBER).eq().item(T_PARENT, AccessCertificationCaseType.F_STAGE_NUMBER) - .and().item(F_OUTPUT, AbstractWorkItemOutputType.F_OUTCOME).isNull() + .item(F_ASSIGNEE_REF).ref("123456") + .and().item(F_STAGE_NUMBER).eq().item(T_PARENT, AccessCertificationCaseType.F_STAGE_NUMBER) + .and().item(F_OUTPUT, AbstractWorkItemOutputType.F_OUTCOME).isNull() .endBlock() .build(); @@ -3742,9 +3691,9 @@ public void test0925DecisionsNotAnsweredOrderBy() throws Exception { ObjectQuery query = prismContext.queryFor(AccessCertificationCaseType.class) .exists(F_WORK_ITEM) .block() - .item(F_ASSIGNEE_REF).ref("123456") - .and().item(F_STAGE_NUMBER).eq().item(T_PARENT, AccessCertificationCaseType.F_STAGE_NUMBER) - .and().item(F_OUTPUT, AbstractWorkItemOutputType.F_OUTCOME).isNull() + .item(F_ASSIGNEE_REF).ref("123456") + .and().item(F_STAGE_NUMBER).eq().item(T_PARENT, AccessCertificationCaseType.F_STAGE_NUMBER) + .and().item(F_OUTPUT, AbstractWorkItemOutputType.F_OUTCOME).isNull() .endBlock() .asc(T_PARENT, F_NAME) .asc(T_ID) @@ -3940,7 +3889,7 @@ public void test0950RedundantBlock() throws Exception { try { ObjectQuery query = prismContext.queryFor(ShadowType.class) .block() - .item(ShadowType.F_NAME).eqPoly("aaa") + .item(ShadowType.F_NAME).eqPoly("aaa") .endBlock() .build(); @@ -3968,9 +3917,9 @@ public void test0952TwoRedundantBlocks() throws Exception { try { ObjectQuery query = prismContext.queryFor(ShadowType.class) .block() - .block() - .item(ShadowType.F_NAME).eqPoly("aaa") - .endBlock() + .block() + .item(ShadowType.F_NAME).eqPoly("aaa") + .endBlock() .endBlock() .build(); @@ -3998,9 +3947,9 @@ public void test0954RedundantBlocksAndExists() throws Exception { try { ObjectQuery query = prismContext.queryFor(ShadowType.class) .block() - .item(ShadowType.F_RESOURCE_REF).ref("111") - .and() - .exists(ShadowType.F_PENDING_OPERATION) + .item(ShadowType.F_RESOURCE_REF).ref("111") + .and() + .exists(ShadowType.F_PENDING_OPERATION) .endBlock() .build(); @@ -4213,7 +4162,7 @@ public void test1180OperationFatalError() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .item(F_OPERATION_EXECUTION, OperationExecutionType.F_STATUS) - .eq(OperationResultStatusType.FATAL_ERROR) + .eq(OperationResultStatusType.FATAL_ERROR) .build(); String real = getInterpretedQuery2(session, ShadowType.class, query); String expected = "select\n" @@ -4236,7 +4185,7 @@ public void test1182OperationFatalErrorTimestampSort() throws Exception { try { ObjectQuery query = prismContext.queryFor(ObjectType.class) .item(F_OPERATION_EXECUTION, OperationExecutionType.F_STATUS) - .eq(OperationResultStatusType.FATAL_ERROR) + .eq(OperationResultStatusType.FATAL_ERROR) .desc(F_OPERATION_EXECUTION, OperationExecutionType.F_TIMESTAMP) .build(); String real = getInterpretedQuery2(session, ShadowType.class, query); @@ -4262,8 +4211,8 @@ public void test1190OperationSuccessForGivenTask() throws Exception { ObjectQuery query = prismContext.queryFor(ObjectType.class) .exists(F_OPERATION_EXECUTION) .block() - .item(OperationExecutionType.F_TASK_REF).ref("oid1") - .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.SUCCESS) + .item(OperationExecutionType.F_TASK_REF).ref("oid1") + .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.SUCCESS) .endBlock() .build(); String real = getInterpretedQuery2(session, ShadowType.class, query); @@ -4294,8 +4243,8 @@ public void test1200OperationLastFailures() throws Exception { ObjectQuery query = prismContext.queryFor(ObjectType.class) .exists(F_OPERATION_EXECUTION) .block() - .item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.FATAL_ERROR) - .and().item(OperationExecutionType.F_TIMESTAMP).le(XmlTypeConverter.createXMLGregorianCalendar(new Date())) + .item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.FATAL_ERROR) + .and().item(OperationExecutionType.F_TIMESTAMP).le(XmlTypeConverter.createXMLGregorianCalendar(new Date())) .endBlock() .build(); String real = getInterpretedQuery2(session, ShadowType.class, query); @@ -4607,7 +4556,6 @@ public void test1320OidGeLtTest() throws Exception { } } - private Collection> distinct() { return createCollection(createDistinct()); } @@ -4616,30 +4564,6 @@ private SqlRepositoryConfiguration getConfiguration() { return sqlRepositoryService.getConfiguration(); } - // @Test -// public void test0930OrganizationEqualsCostCenter() throws Exception { -// Session session = open(); -// -// try { -// /* -// * ### User: organization = costCenter -// */ -// ObjectQuery query = ObjectQuery.createObjectQuery( -// EqualFilter.createEqual( -// ItemPath.create(UserType.F_ORGANIZATION), -// UserType.class, -// prismContext, -// null, -// ItemPath.create(UserType.F_COST_CENTER))); -// -// String real = getInterpretedQuery2(session, UserType.class, query); -//// assertEqualsIgnoreWhitespace(expected, real); -// } finally { -// close(session); -// } -// } - - // TODO negative tests - order by entity, reference, any, collection // TODO implement checks for "order by" for non-singletons @@ -4659,13 +4583,13 @@ private ObjectQuery getQuery(File file, Class type) throws SchemaException, IOException { QueryType queryType = PrismTestUtil.parseAtomicValue(file, QueryType.COMPLEX_TYPE); - LOGGER.info("QUERY TYPE TO CONVERT : {}", ObjectQueryUtil.dump(queryType, prismContext)); + logger.info("QUERY TYPE TO CONVERT : {}", ObjectQueryUtil.dump(queryType, prismContext)); ObjectQuery query = null; try { query = getQueryConverter().createObjectQuery(type, queryType); // TODO } catch (Exception ex) { - LOGGER.info("error while converting query: " + ex.getMessage(), ex); + logger.info("error while converting query: " + ex.getMessage(), ex); } return query; } @@ -4678,7 +4602,6 @@ protected String getInterpretedQuery2(Session session, return getInterpretedQuery2(session, type, query, false); } - protected String getInterpretedQuery2(Session session, Class type, ObjectQuery query, boolean interpretCount) throws Exception { return getInterpretedQuery2(session, type, query, interpretCount, null); @@ -4695,7 +4618,7 @@ private RQuery getInterpretedQuery2Whole(Session sessi boolean interpretCount, Collection> options) throws QueryException { if (query != null) { - LOGGER.info("QUERY TYPE TO CONVERT :\n{}", (query.getFilter() != null ? query.getFilter().debugDump(3) : null)); + logger.info("QUERY TYPE TO CONVERT :\n{}", (query.getFilter() != null ? query.getFilter().debugDump(3) : null)); } QueryEngine2 engine = new QueryEngine2(baseHelper.getConfiguration(), extItemDictionary, prismContext, relationRegistry); @@ -4710,13 +4633,13 @@ private RQuery getInterpretedQuery2Whole(Session sessi } private void assertEqualsIgnoreWhitespace(String expected, String real) { - LOGGER.info("exp. query>\n{}\nreal query>\n{}", expected, real); + logger.info("exp. query>\n{}\nreal query>\n{}", expected, real); String expNorm = StringUtils.normalizeSpace(expected); String realNorm = StringUtils.normalizeSpace(real); if (!expNorm.equals(realNorm)) { String m = "Generated query is not correct. Expected:\n" + expected + "\nActual:\n" + real + "\n\nNormalized versions:\n\n" + "Expected: " + expNorm + "\nActual: " + realNorm + "\n"; - LOGGER.error("{}", m); + logger.error("{}", m); throw new AssertionError(m); } } @@ -4946,6 +4869,7 @@ public void test1443QueryNameNull() throws Exception { } //@Test + @UnusedTestElement public void test1443QueryWithMultiValueItemPathForOrdering() throws Exception { Session session = open(); try { @@ -4976,5 +4900,4 @@ public void test1443QueryWithMultiValueItemPathForOrdering() throws Exception { close(session); } } - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RAnyConverterStaticTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RAnyConverterStaticTest.java index 912caedc0b8..3e94527e285 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RAnyConverterStaticTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RAnyConverterStaticTest.java @@ -8,8 +8,21 @@ package com.evolveum.midpoint.repo.sql; import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +import org.hibernate.Session; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; -import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismConstants; +import com.evolveum.midpoint.prism.PrismObjectDefinition; +import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; @@ -21,33 +34,15 @@ import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.BeforeAfterType; import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.hibernate.Session; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; - -/** - * @author lazyman - */ - -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class RAnyConverterStaticTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(RAnyConverterStaticTest.class); private static final String NS_P = "http://example.com/p"; private static final String NS_T = PrismConstants.NS_TYPES; private static final String NS_FOO_RESOURCE = "http://example.com/foo"; diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RUtilTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RUtilTest.java index 719d4520d86..7153bdc783c 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RUtilTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/RUtilTest.java @@ -6,28 +6,25 @@ */ package com.evolveum.midpoint.repo.sql; -import com.evolveum.midpoint.repo.sql.util.RUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import java.io.File; +import java.io.FileInputStream; +import java.nio.charset.StandardCharsets; + import org.apache.commons.io.IOUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; -import java.io.File; -import java.io.FileInputStream; -import java.nio.charset.StandardCharsets; +import com.evolveum.midpoint.repo.sql.util.RUtil; /** * @author lazyman */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class RUtilTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(RUtilTest.class); - private static final String USER_BIG = "user-big.xml"; @Test @@ -36,7 +33,7 @@ public void test100XmlToByteArrayCompressionEnabled() throws Exception { new File(BaseSQLRepoTest.FOLDER_BASIC, USER_BIG)), StandardCharsets.UTF_8.name()); byte[] array = RUtil.getByteArrayFromXml(xml, true); - LOGGER.info("Compression ratio: {}", getCompressRatio(xml.getBytes( StandardCharsets.UTF_8.name()).length, array.length)); + logger.info("Compression ratio: {}", getCompressRatio(xml.getBytes(StandardCharsets.UTF_8.name()).length, array.length)); String xmlNew = RUtil.getXmlFromByteArray(array, true); @@ -46,12 +43,12 @@ public void test100XmlToByteArrayCompressionEnabled() throws Exception { @Test public void test200XmlToByteArrayCompressionDisabled() throws Exception { String xml = IOUtils.toString(new FileInputStream( - new File(BaseSQLRepoTest.FOLDER_BASIC, USER_BIG)), StandardCharsets.UTF_8.name()); + new File(BaseSQLRepoTest.FOLDER_BASIC, USER_BIG)), StandardCharsets.UTF_8.name()); byte[] array = RUtil.getByteArrayFromXml(xml, false); - LOGGER.info("Compression ratio: {}", getCompressRatio(xml.getBytes( StandardCharsets.UTF_8.name()).length, array.length)); + logger.info("Compression ratio: {}", getCompressRatio(xml.getBytes(StandardCharsets.UTF_8.name()).length, array.length)); - AssertJUnit.assertEquals(xml.getBytes( StandardCharsets.UTF_8.name()), array); + AssertJUnit.assertEquals(xml.getBytes(StandardCharsets.UTF_8.name()), array); String xmlNew = RUtil.getXmlFromByteArray(array, false); @@ -61,7 +58,7 @@ public void test200XmlToByteArrayCompressionDisabled() throws Exception { @Test public void test250ByteArrayToXmlShouldBeCompressed() throws Exception { String xml = IOUtils.toString(new FileInputStream( - new File(BaseSQLRepoTest.FOLDER_BASIC, USER_BIG)), StandardCharsets.UTF_8.name()); + new File(BaseSQLRepoTest.FOLDER_BASIC, USER_BIG)), StandardCharsets.UTF_8.name()); byte[] array = RUtil.getByteArrayFromXml(xml, false); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java index 53111cad4e4..8ae7c739e92 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java @@ -30,8 +30,6 @@ import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; /** @@ -41,7 +39,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ResourceModifyTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(ResourceModifyTest.class); private static final File TEST_DIR = new File("src/test/resources/modify"); private static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); @@ -63,7 +60,7 @@ public void initAnts() { @Test public void test010AddResource() throws Exception { final String TEST_NAME = "test010AddResource"; - LOGGER.info("===[ {} ]===", TEST_NAME); + logger.info("===[ {} ]===", TEST_NAME); // GIVEN OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); @@ -85,7 +82,7 @@ public void test010AddResource() throws Exception { @Test public void test020SingleDescriptionModify() throws Exception { final String TEST_NAME = "test020SingleDescriptionModify"; - LOGGER.info("===[ {} ]===", TEST_NAME); + logger.info("===[ {} ]===", TEST_NAME); OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); singleModify(descriptionAnt, -1, result); @@ -94,7 +91,7 @@ public void test020SingleDescriptionModify() throws Exception { @Test public void test030DescriptionModifySequence() throws Exception { final String TEST_NAME = "test030DescriptionModifySequence"; - LOGGER.info("===[ {} ]===", TEST_NAME); + logger.info("===[ {} ]===", TEST_NAME); OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); @@ -106,7 +103,7 @@ public void test030DescriptionModifySequence() throws Exception { @Test public void test040RadomModifySequence() throws Exception { final String TEST_NAME = "test040RadomModifySequence"; - LOGGER.info("===[ {} ]===", TEST_NAME); + logger.info("===[ {} ]===", TEST_NAME); OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchIterativeTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchIterativeTest.java index 2804ba051f1..c77d9ce8b50 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchIterativeTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchIterativeTest.java @@ -7,55 +7,41 @@ package com.evolveum.midpoint.repo.sql; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.repo.api.RepositoryService.OP_SEARCH_OBJECTS; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.sql.perf.SqlPerformanceMonitorImpl; -import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.List; -import static com.evolveum.midpoint.repo.api.RepositoryService.OP_SEARCH_OBJECTS; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; - -/** - * @author mederly - */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class SearchIterativeTest extends BaseSQLRepoTest { - @SuppressWarnings("unused") - private static final Trace LOGGER = TraceManager.getTrace(SearchIterativeTest.class); private static final int BASE = 100000; private static final int COUNT = 500; // should be divisible by BATCH private static final int BATCH = 50; // should be synchronized with repo setting - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - + @Override + public void initSystem() throws Exception { createObjects(); } @@ -64,7 +50,7 @@ private void createObjects() throws com.evolveum.midpoint.util.exception.ObjectA for (int i = BASE; i < BASE + COUNT; i++) { UserType user = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class).instantiate().asObjectable(); user.setOid("user-" + i + "-00"); - user.setName(new PolyStringType(new PolyString("user-"+i))); + user.setName(new PolyStringType(new PolyString("user-" + i))); user.setCostCenter(String.valueOf(i)); repositoryService.addObject(user.asPrismObject(), null, result); } @@ -288,7 +274,7 @@ public void test120DeleteHalf() throws Exception { assertObjects(objects, COUNT); int count = repositoryService.countObjects(UserType.class, null, null, result); - assertEquals("Wrong # of objects after operation", COUNT/2, count); + assertEquals("Wrong # of objects after operation", COUNT / 2, count); ObjectQuery query = prismContext.queryFor(UserType.class) .asc(UserType.F_NAME) @@ -307,18 +293,18 @@ public void test130AddOneForOne() throws Exception { ResultHandler handler = (object, parentResult) -> { objects.add(object); System.out.print("Got object " + object.getOid()); - LOGGER.info("Got object {} ({})", object.getOid(), object.asObjectable().getName().getOrig()); + logger.info("Got object {} ({})", object.getOid(), object.asObjectable().getName().getOrig()); try { int number = Integer.parseInt(object.asObjectable().getCostCenter()); if (number >= 0) { UserType user = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class).instantiate().asObjectable(); - user.setOid("user-" + (2*BASE + COUNT - number) + "-FF"); + user.setOid("user-" + (2 * BASE + COUNT - number) + "-FF"); user.setName(new PolyStringType(new PolyString("user-new-" + number))); user.setCostCenter(String.valueOf(-number)); repositoryService.addObject(user.asPrismObject(), null, parentResult); System.out.print(" ... creating object " + user.getOid()); } - } catch (ObjectAlreadyExistsException|SchemaException e) { + } catch (ObjectAlreadyExistsException | SchemaException e) { throw new SystemException(e); } System.out.println(); @@ -332,9 +318,9 @@ public void test130AddOneForOne() throws Exception { boolean[] map = assertObjects(objects, null); for (int i = 0; i < COUNT; i++) { if (i % 2 == 0) { - assertFalse("Object " + (BASE+i) + " does exist but it should not", map[i]); + assertFalse("Object " + (BASE + i) + " does exist but it should not", map[i]); } else { - assertTrue("Object " + (BASE+i) + " does not exist but it should", map[i]); + assertTrue("Object " + (BASE + i) + " does not exist but it should", map[i]); } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchShadowOwnerTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchShadowOwnerTest.java index b8f94e00e09..78cace7e5e0 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchShadowOwnerTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchShadowOwnerTest.java @@ -11,8 +11,6 @@ import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; @@ -35,10 +33,8 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class SearchShadowOwnerTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(SearchShadowOwnerTest.class); - @Test - public void searchNonExistingShadowOwner() throws Exception { + public void searchNonExistingShadowOwner() { //searching owner for non existing shadow OperationResult result = new OperationResult("List owner"); PrismObject shadow = repositoryService.searchShadowOwner("12345", null, result); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchTest.java index db2c9fd79c2..65ece56b94b 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SearchTest.java @@ -7,61 +7,54 @@ package com.evolveum.midpoint.repo.sql; -import com.evolveum.midpoint.prism.*; +import static java.util.Collections.emptySet; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.repo.api.RepoModifyOptions.createExecuteIfNoChanges; +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; + +import java.io.File; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.Objectable; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.OrderDirection; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.*; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.ResultHandler; +import com.evolveum.midpoint.schema.SearchResultList; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; -import java.io.File; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; - -import static com.evolveum.midpoint.repo.api.RepoModifyOptions.createExecuteIfNoChanges; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType.F_NAME; - -import static java.util.Collections.emptySet; -import static org.testng.AssertJUnit.*; - -/** - * @author lazyman - */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class SearchTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(SearchTest.class); private static final String DESCRIPTION_TO_FIND = "tralala"; private static final String ARCHETYPE1_OID = "a71e48fe-f6e2-40f4-ab76-b4ad4a0918ad"; private String beforeConfigOid; - @BeforeClass - public void beforeClass() throws Exception { - super.beforeClass(); - - PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - + @Override + public void initSystem() throws Exception { OperationResult result = new OperationResult("add objects"); PrismObject beforeConfig = prismContext.createObjectable(UserType.class) .name("before-config") @@ -75,7 +68,7 @@ public void beforeClass() throws Exception { entry.getItem().add(new ItemPathType(ObjectType.F_DESCRIPTION)); fullTextConfig.getIndexed().add(entry); repositoryService.applyFullTextSearchConfiguration(fullTextConfig); - LOGGER.info("Applying full text search configuration: {}", fullTextConfig); + logger.info("Applying full text search configuration: {}", fullTextConfig); List> objects = prismContext.parserFor(new File(FOLDER_BASIC, "objects.xml")).parseObjects(); objects.addAll(prismContext.parserFor(new File(FOLDER_BASIC, "objects-2.xml")).parseObjects()); @@ -143,6 +136,7 @@ private void iterateGeneral(int offset, int size, int batch, final String... nam ResultHandler handler = new ResultHandler() { private int index = 0; + @Override public boolean handle(PrismObject object, OperationResult parentResult) { objects.add(object); @@ -155,7 +149,7 @@ public boolean handle(PrismObject object, OperationResult parentResult int oldBatchSize = config.getIterativeSearchByPagingBatchSize(); config.setIterativeSearchByPagingBatchSize(batch); - LOGGER.trace(">>>>>> iterateGeneral: offset = " + offset + ", size = " + size + ", batch = " + batch + " <<<<<<"); + logger.trace(">>>>>> iterateGeneral: offset = " + offset + ", size = " + size + ", batch = " + batch + " <<<<<<"); ObjectQuery query = prismContext.queryFactory().createQuery(); query.setPaging(prismContext.queryFactory().createPaging(offset, size, ObjectType.F_NAME, OrderDirection.ASCENDING)); @@ -412,7 +406,7 @@ public void notBusinessRoleTypeSearchTest() throws Exception { int judge = roles.get(0).getName().getOrig().startsWith("J") ? 0 : 1; assertEquals("Wrong role1 name", "Judge", roles.get(judge).getName().getOrig()); - assertEquals("Wrong role2 name", "Admin-owned role", roles.get(1-judge).getName().getOrig()); + assertEquals("Wrong role2 name", "Admin-owned role", roles.get(1 - judge).getName().getOrig()); } @Test @@ -442,7 +436,7 @@ public void emptyRoleTypeSearchTest() throws Exception { int judge = roles.get(0).getName().getOrig().startsWith("J") ? 0 : 1; assertEquals("Wrong role1 name", "Judge", roles.get(judge).getName().getOrig()); - assertEquals("Wrong role2 name", "Admin-owned role", roles.get(1-judge).getName().getOrig()); + assertEquals("Wrong role2 name", "Admin-owned role", roles.get(1 - judge).getName().getOrig()); } @Test @@ -515,7 +509,7 @@ private void testOwnerRef(Class clazz, String oid, String. private void testOwnerRefWithTypeRestriction(Class clazz, String oid, String... names) throws SchemaException { ObjectQuery query = prismContext.queryFor(ObjectType.class) .type(clazz) - .item(new QName(SchemaConstants.NS_C, "ownerRef")).ref(oid) + .item(new QName(SchemaConstants.NS_C, "ownerRef")).ref(oid) .build(); checkResult(ObjectType.class, clazz, oid, query, names); } @@ -638,18 +632,18 @@ public void caseInsensitiveSearchTest() throws Exception { false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_FULL_NAME).eqPoly(existingNameOrig).matchingNorm() - .build(), + .item(UserType.F_FULL_NAME).eqPoly(existingNameOrig).matchingNorm() + .build(), false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_EMAIL_ADDRESS).eq(emailLowerCase).matchingCaseIgnore() - .build(), + .item(UserType.F_EMAIL_ADDRESS).eq(emailLowerCase).matchingCaseIgnore() + .build(), false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_EMAIL_ADDRESS).eq(emailVariousCase).matchingCaseIgnore() - .build(), + .item(UserType.F_EMAIL_ADDRESS).eq(emailVariousCase).matchingCaseIgnore() + .build(), false, 1); // comparing polystrings, but providing plain String @@ -669,18 +663,18 @@ public void caseInsensitiveSearchTest() throws Exception { false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_FULL_NAME).containsPoly(existingNameOrig).matchingNorm() - .build(), + .item(UserType.F_FULL_NAME).containsPoly(existingNameOrig).matchingNorm() + .build(), false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_EMAIL_ADDRESS).contains(emailLowerCase).matchingCaseIgnore() - .build(), + .item(UserType.F_EMAIL_ADDRESS).contains(emailLowerCase).matchingCaseIgnore() + .build(), false, 1); assertUsersFound(prismContext.queryFor(UserType.class) - .item(UserType.F_EMAIL_ADDRESS).contains(emailVariousCase).matchingCaseIgnore() - .build(), + .item(UserType.F_EMAIL_ADDRESS).contains(emailVariousCase).matchingCaseIgnore() + .build(), false, 1); // comparing polystrings, but providing plain String @@ -745,7 +739,7 @@ public void fullTextSearch() throws Exception { + "\t\t\tVestibulum vel pulvinar ligula, vitae rutrum leo. Sed efficitur dignissim augue in placerat. Aliquam dapibus mauris\n" + "\t\t\teget diam pharetra molestie. Morbi vitae nulla sollicitudin, dignissim tellus a, tincidunt neque.\n"; - LOGGER.info("## changing description ##"); + logger.info("## changing description ##"); repositoryService.modifyObject(UserType.class, users.get(0).getOid(), prismContext.deltaFor(UserType.class) .item(UserType.F_DESCRIPTION).replace(newDescription) @@ -753,7 +747,7 @@ public void fullTextSearch() throws Exception { result); // just to see SQL used - LOGGER.info("## changing telephoneNumber ##"); + logger.info("## changing telephoneNumber ##"); repositoryService.modifyObject(UserType.class, users.get(0).getOid(), prismContext.deltaFor(UserType.class) .item(UserType.F_TELEPHONE_NUMBER).replace("123456") @@ -869,10 +863,10 @@ public void testOperationExecutionAny() throws SchemaException { public void testOperationExecutionWithTask() throws SchemaException { ObjectQuery query = prismContext.queryFor(CaseType.class) .exists(ObjectType.F_OPERATION_EXECUTION) - .block() - .item(OperationExecutionType.F_TASK_REF).ref("task-oid-2") - .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.SUCCESS) - .endBlock() + .block() + .item(OperationExecutionType.F_TASK_REF).ref("task-oid-2") + .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.SUCCESS) + .endBlock() .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(CaseType.class, query, null, result); @@ -885,10 +879,10 @@ public void testOperationExecutionWithTask() throws SchemaException { public void testOperationExecutionWithTask2() throws SchemaException { ObjectQuery query = prismContext.queryFor(CaseType.class) .exists(ObjectType.F_OPERATION_EXECUTION) - .block() - .item(OperationExecutionType.F_TASK_REF).ref("task-oid-2") - .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.FATAL_ERROR) - .endBlock() + .block() + .item(OperationExecutionType.F_TASK_REF).ref("task-oid-2") + .and().item(OperationExecutionType.F_STATUS).eq(OperationResultStatusType.FATAL_ERROR) + .endBlock() .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(CaseType.class, query, null, result); @@ -901,7 +895,7 @@ public void testOperationExecutionWithTask2() throws SchemaException { public void testExtensionReference() throws SchemaException { ObjectQuery query = prismContext.queryFor(GenericObjectType.class) .item(ObjectType.F_EXTENSION, new QName("referenceType")) - .ref("12345678-1234-1234-1234-123456789012") + .ref("12345678-1234-1234-1234-123456789012") .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(GenericObjectType.class, query, null, result); @@ -914,7 +908,7 @@ public void testExtensionReference() throws SchemaException { public void testExtensionReferenceNotMatching() throws SchemaException { ObjectQuery query = prismContext.queryFor(GenericObjectType.class) .item(ObjectType.F_EXTENSION, new QName("referenceType")) - .ref("12345678-1234-1234-1234-123456789xxx") + .ref("12345678-1234-1234-1234-123456789xxx") .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(GenericObjectType.class, query, null, result); @@ -927,7 +921,7 @@ public void testExtensionReferenceNotMatching() throws SchemaException { public void testExtensionReferenceNull() throws SchemaException { ObjectQuery query = prismContext.queryFor(GenericObjectType.class) .item(ObjectType.F_EXTENSION, new QName("referenceType")) - .isNull() + .isNull() .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(GenericObjectType.class, query, null, result); @@ -940,7 +934,7 @@ public void testExtensionReferenceNull() throws SchemaException { public void testExtensionReferenceNonNull() throws SchemaException { ObjectQuery query = prismContext.queryFor(GenericObjectType.class) .not().item(ObjectType.F_EXTENSION, new QName("referenceType")) - .isNull() + .isNull() .build(); OperationResult result = new OperationResult("search"); List> cases = repositoryService.searchObjects(GenericObjectType.class, query, null, result); diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SequenceTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SequenceTest.java index 64e1d027289..03b0ce752c0 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SequenceTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/SequenceTest.java @@ -13,8 +13,6 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SequenceType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; import org.hibernate.Session; @@ -42,8 +40,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class SequenceTest extends BaseSQLRepoTest { - private static final Trace LOGGER = TraceManager.getTrace(SequenceTest.class); - private static final String TEST_DIR = "src/test/resources/sequence/"; private static final int STOP_TIMEOUT = 10000; @@ -208,16 +204,16 @@ public void execute(Connection connection) throws SQLException { OperationResult result = new OperationResult("Concurrency Test"); String oid = repositoryService.addObject(sequence, null, result); - LOGGER.info("*** Object added: " + oid + " ***"); + logger.info("*** Object added: " + oid + " ***"); - LOGGER.info("*** Starting modifier threads ***"); + logger.info("*** Starting modifier threads ***"); for (WorkerThread t : workerThreads) { t.setOid(oid); t.start(); } - LOGGER.info("*** Waiting " + duration + " ms ***"); + logger.info("*** Waiting " + duration + " ms ***"); Thread.sleep(duration); for (WorkerThread t : workerThreads) { @@ -240,7 +236,7 @@ public void execute(Connection connection) throws SQLException { } for (WorkerThread t : workerThreads) { - LOGGER.info("Worker thread {} finished after {} iterations with result: {}", t.id, t.counter, t.threadResult != null ? t.threadResult : "OK"); + logger.info("Worker thread {} finished after {} iterations with result: {}", t.id, t.counter, t.threadResult != null ? t.threadResult : "OK"); } for (WorkerThread t : workerThreads) { @@ -256,12 +252,12 @@ public void execute(Connection connection) throws SQLException { if (alwaysOrder || workerThreads.length > 1) { Collections.sort(allValues); } - LOGGER.trace("Checking a list of {} values", allValues.size()); + logger.trace("Checking a list of {} values", allValues.size()); for (int i = 0; i < allValues.size(); i++) { if (allValues.get(i) != i) { - LOGGER.error("Incorrect value at position {}: {}", i, allValues.get(i)); + logger.error("Incorrect value at position {}: {}", i, allValues.get(i)); for (WorkerThread t : workerThreads) { - LOGGER.info("Thread {}: {}", t.id, t.values); + logger.info("Thread {}: {}", t.id, t.values); } fail("Incorrect value at position " + i + ": " + allValues.get(i)); } @@ -298,7 +294,7 @@ public void run() { counter++; } } catch (Throwable t) { - LoggingUtils.logException(LOGGER, "Unexpected exception: " + t, t); + LoggingUtils.logException(logger, "Unexpected exception: " + t, t); threadResult = t; } } @@ -306,7 +302,7 @@ public void run() { public void runOnce() throws SchemaException, ObjectNotFoundException { OperationResult result = new OperationResult("run"); long value = repositoryService.advanceSequence(oid, result); - LOGGER.debug("Advance sequence returned {}", value); + logger.debug("Advance sequence returned {}", value); values.add(value); if (returnEach > 0) { if (countToReturn > 0) { @@ -321,7 +317,7 @@ public void runOnce() throws SchemaException, ObjectNotFoundException { } catch (InterruptedException e) { } value = repositoryService.advanceSequence(oid, result); - LOGGER.debug("Advance sequence returned {} (after return)", value); + logger.debug("Advance sequence returned {} (after return)", value); values.add(value); } } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/AbstractOrgClosureTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/AbstractOrgClosureTest.java index 4b7b9113dd4..a97ffd34d64 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/AbstractOrgClosureTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/AbstractOrgClosureTest.java @@ -7,11 +7,29 @@ package com.evolveum.midpoint.repo.sql.closure; +import static org.testng.AssertJUnit.*; + +import java.util.*; +import javax.xml.namespace.QName; + import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import cern.colt.matrix.linalg.Algebra; import cern.jet.math.Functions; -import com.evolveum.midpoint.prism.*; +import org.apache.commons.lang.StringUtils; +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.hibernate.type.LongType; +import org.hibernate.type.StringType; +import org.jgrapht.alg.TransitiveClosure; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.SimpleDirectedGraph; +import org.springframework.beans.factory.annotation.Autowired; + +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismObjectDefinition; +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; @@ -21,37 +39,14 @@ import com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager; import com.evolveum.midpoint.repo.sql.type.XMLGregorianCalendarType; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -import org.apache.commons.lang.StringUtils; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.type.LongType; -import org.hibernate.type.StringType; -import org.jgrapht.alg.TransitiveClosure; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.SimpleDirectedGraph; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.xml.namespace.QName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; /** * @author lazyman @@ -62,8 +57,6 @@ public abstract class AbstractOrgClosureTest extends BaseSQLRepoTest { @Autowired private OrgClosureManager closureManager; - private static final Trace LOGGER = TraceManager.getTrace(AbstractOrgClosureTest.class); - // The following attributes describe the object graph as originally created/scanned. // Subsequent operations (add/remove node or link) DO NOT change these. @@ -111,15 +104,15 @@ private void checkChildrenSets(Set oidsToCheck) { SimpleDirectedGraph tc = (SimpleDirectedGraph) orgGraph.clone(); TransitiveClosure.INSTANCE.closeSimpleDirectedGraph(tc); for (String subroot : oidsToCheck) { - LOGGER.info("Checking descendants of {}", subroot); + logger.info("Checking descendants of {}", subroot); Set expectedChildren = new HashSet<>(); for (DefaultEdge edge : tc.incomingEdgesOf(subroot)) { expectedChildren.add(tc.getEdgeSource(edge)); } expectedChildren.add(subroot); - LOGGER.trace("Expected children: {}", expectedChildren); + logger.trace("Expected children: {}", expectedChildren); Set actualChildren = getActualChildrenOf(subroot, session); - LOGGER.trace("Actual children: {}", actualChildren); + logger.trace("Actual children: {}", actualChildren); Set expectedMinusActual = new HashSet<>(expectedChildren); expectedMinusActual.removeAll(actualChildren); @@ -151,8 +144,7 @@ protected boolean checkClosureMatrix() throws SchemaException { // used to give indices to vertices List vertexList = new ArrayList<>(getVertices()); - if (DUMP_TC_MATRIX_DETAILS) - LOGGER.info("Vertex list = {}", vertexList); + if (DUMP_TC_MATRIX_DETAILS) { logger.info("Vertex list = {}", vertexList); } DoubleMatrix2D a = new SparseDoubleMatrix2D(vertices, vertices); // for (int i = 0; i < vertices; i++) { @@ -177,17 +169,16 @@ protected boolean checkClosureMatrix() throws SchemaException { // System.out.println("a=" + a); // System.out.println("a^"+level+"="+power); } - LOGGER.info("TC matrix computed in {} ms", System.currentTimeMillis() - start); + logger.info("TC matrix computed in {} ms", System.currentTimeMillis() - start); - if (DUMP_TC_MATRIX_DETAILS) - LOGGER.info("TC matrix expected = {}", result); + if (DUMP_TC_MATRIX_DETAILS) { logger.info("TC matrix expected = {}", result); } Query q = session.createNativeQuery("select descendant_oid, ancestor_oid, val from m_org_closure") .addScalar("descendant_oid", StringType.INSTANCE) .addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", LongType.INSTANCE); List list = q.list(); - LOGGER.info("OrgClosure has {} rows", list.size()); + logger.info("OrgClosure has {} rows", list.size()); DoubleMatrix2D closureInDatabase = new SparseDoubleMatrix2D(vertices, vertices); for (Object[] item : list) { @@ -200,18 +191,16 @@ protected boolean checkClosureMatrix() throws SchemaException { val); } - if (DUMP_TC_MATRIX_DETAILS) - LOGGER.info("TC matrix fetched from db = {}", closureInDatabase); + if (DUMP_TC_MATRIX_DETAILS) { logger.info("TC matrix fetched from db = {}", closureInDatabase); } double zSumResultBefore = result.zSum(); double zSumClosureInDb = closureInDatabase.zSum(); result.assign(closureInDatabase, Functions.minus); double zSumResultAfter = result.zSum(); - LOGGER.info("Summary of items in closure computed: {}, in DB-stored closure: {}, delta: {}", + logger.info("Summary of items in closure computed: {}, in DB-stored closure: {}, delta: {}", zSumResultBefore, zSumClosureInDb, zSumResultAfter); - if (DUMP_TC_MATRIX_DETAILS) - LOGGER.info("Difference matrix = {}", result); + if (DUMP_TC_MATRIX_DETAILS) { logger.info("Difference matrix = {}", result); } boolean problem = false; for (int i = 0; i < vertices; i++) { @@ -221,7 +210,7 @@ protected boolean checkClosureMatrix() throws SchemaException { System.err.println("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta + " (closureInDB=" + closureInDatabase.get(i, j) + ", expected=" + (result.get(i, j) + closureInDatabase.get(i, j)) + ")"); - LOGGER.error("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta); + logger.error("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta); problem = true; } } @@ -245,7 +234,7 @@ protected void checkOrgGraph() throws SchemaException { OrgType orgType; try { orgType = repositoryService.getObject(OrgType.class, oid, null, result).asObjectable(); - } catch (ObjectNotFoundException|SchemaException e) { + } catch (ObjectNotFoundException | SchemaException e) { throw new AssertionError("Couldn't fetch " + oid, e); } assertTrue(orgGraph.vertexSet().contains(orgType.getOid())); @@ -355,7 +344,7 @@ protected void reAddUser(UserType user, OperationResult opResult) throws Excepti // parentsInLevel may be null (in that case, a simple tree is generated) protected void loadOrgStructure(int level, String parentOid, String oidPrefix, - OperationResult result) throws Exception { + OperationResult result) throws Exception { int[] orgChildrenInLevel = getConfiguration().getOrgChildrenInLevel(); int[] userChildrenInLevel = getConfiguration().getUserChildrenInLevel(); @@ -373,9 +362,9 @@ protected void loadOrgStructure(int level, String parentOid, String oidPrefix, for (int i = 0; i < orgChildrenInLevel[level]; i++) { String newOidPrefix = getOidCharFor(i) + oidPrefix; - int numberOfParents = parentsInLevel==null ? (parentOid != null ? 1 : 0) : parentsInLevel[level]; + int numberOfParents = parentsInLevel == null ? (parentOid != null ? 1 : 0) : parentsInLevel[level]; PrismObject org = createOrg(generateParentsForLevel(parentOid, level, numberOfParents), newOidPrefix); - LOGGER.info("Creating {}, total {}; parents = {}", new Object[]{org, objectCount, getParentsOids(org)}); + logger.info("Creating {}, total {}; parents = {}", new Object[] { org, objectCount, getParentsOids(org) }); String oid = repositoryService.addObject(org, null, result); org.setOid(oid); if (parentOid == null) { @@ -389,7 +378,7 @@ protected void loadOrgStructure(int level, String parentOid, String oidPrefix, info(objectCount + " objects created"); } - loadOrgStructure(level+1, oid, newOidPrefix, result); + loadOrgStructure(level + 1, oid, newOidPrefix, result); } if (parentOid != null && userChildrenInLevel != null) { @@ -397,9 +386,9 @@ protected void loadOrgStructure(int level, String parentOid, String oidPrefix, List usersAtThisLevel = getUsersAtThisLevelSafe(level); for (int u = 0; u < userChildrenInLevel[level]; u++) { - int numberOfParents = parentsInLevel==null ? 1 : parentsInLevel[level]; + int numberOfParents = parentsInLevel == null ? 1 : parentsInLevel[level]; PrismObject user = createUser(generateParentsForLevel(parentOid, level, numberOfParents), getOidCharFor(u) + ":" + oidPrefix); - LOGGER.info("Creating {}, total {}; parents = {}", new Object[]{user, objectCount, getParentsOids(user)}); + logger.info("Creating {}, total {}; parents = {}", new Object[] { user, objectCount, getParentsOids(user) }); String uoid = repositoryService.addObject(user, null, result); user.setOid(uoid); allUsersCreated.add(user.asObjectable()); @@ -427,54 +416,11 @@ protected List getOrgsAtThisLevelSafe(int level) { return orgsByLevels.get(level); } - -// // todo better name -// protected void prepareOrgStructureOids(int level, String parentOid, int[] orgChildrenInLevel, int[] userChildrenInLevel, int[] parentsInLevel, String oidPrefix, -// OperationResult result) throws Exception { -// if (level == orgChildrenInLevel.length) { -// return; -// } -// -// List orgsAtThisLevel = getOrgsAtThisLevelSafe(level); -// for (int i = 0; i < orgChildrenInLevel[level]; i++) { -// String newOidPrefix = getOidCharFor(i) + oidPrefix; -// int numberOfParents = parentsInLevel==null ? (parentOid != null ? 1 : 0) : parentsInLevel[level]; -// PrismObject org = createOrg(generateParentsForLevel(parentOid, level, numberOfParents), newOidPrefix); -// LOGGER.info("'Creating' {}, total {}; parents = {}", new Object[]{org, count, getParentsOids(org)}); -// String oid = org.getOid(); -// if (parentOid == null) { -// rootOids.add(oid); -// } -// allOrgCreated.add(org.asObjectable()); -// registerObject(org.asObjectable(), false); -// orgsAtThisLevel.add(oid); -// count++; -// -// prepareOrgStructureOids(level + 1, oid, orgChildrenInLevel, userChildrenInLevel, parentsInLevel, newOidPrefix, result); -// } -// -// if (parentOid != null) { -// -// List usersAtThisLevel = getUsersAtThisLevelSafe(level); -// -// for (int u = 0; u < userChildrenInLevel[level]; u++) { -// int numberOfParents = parentsInLevel==null ? 1 : parentsInLevel[level]; -// PrismObject user = createUser(generateParentsForLevel(parentOid, level, numberOfParents), getOidCharFor(u) + ":" + oidPrefix); -// LOGGER.info("'Creating' {}, total {}; parents = {}", new Object[]{user, count, getParentsOids(user)}); -// String uoid = user.getOid(); -// registerObject(user.asObjectable(), false); -// usersAtThisLevel.add(uoid); -// count++; -// } -// } -// -// } - protected void scanOrgStructure(OperationResult opResult) throws SchemaException, ObjectNotFoundException { // determine rootOids for (int i = 0; ; i++) { - String oid = "o" + createOid(""+getOidCharFor(i)); + String oid = "o" + createOid("" + getOidCharFor(i)); try { System.out.println("Trying to find " + oid + " as a root"); OrgType org = repositoryService.getObject(OrgType.class, oid, null, opResult).asObjectable(); @@ -531,15 +477,15 @@ protected void scanChildren(int level, String parentOid, OperationResult opResul } } + private static final String SPECIAL = "!@#$%^&*()"; - private static final String SPECIAL="!@#$%^&*()"; protected char getOidCharFor(int i) { if (i < 10) { - return (char) ('0'+i); + return (char) ('0' + i); } else if (i < 36) { - return (char) ('A'+i-10); + return (char) ('A' + i - 10); } else if (i < 46) { - return SPECIAL.charAt(i-36); + return SPECIAL.charAt(i - 36); } else { throw new IllegalArgumentException("Too many items in a level: " + i); } @@ -547,7 +493,7 @@ protected char getOidCharFor(int i) { protected Collection getParentsOids(PrismObject object) { List retval = new ArrayList<>(); - for(ObjectReferenceType objectReferenceType : object.asObjectable().getParentOrgRef()) { + for (ObjectReferenceType objectReferenceType : object.asObjectable().getParentOrgRef()) { retval.add(objectReferenceType.getOid()); } return retval; @@ -565,7 +511,7 @@ private List generateParentsForLevel(String explicitParentOid, int level totalParents--; } while (totalParents > 0 && !potentialParents.isEmpty()) { - int i = (int) Math.floor(Math.random()*potentialParents.size()); + int i = (int) Math.floor(Math.random() * potentialParents.size()); rv.add(potentialParents.get(i)); potentialParents.remove(i); totalParents--; @@ -578,7 +524,7 @@ protected void registerObject(ObjectType objectType, boolean registerChildrenLin return; } String oid = objectType.getOid(); - LOGGER.info("Registering {} into memory graph", oid); + logger.info("Registering {} into memory graph", oid); registerVertexIfNeeded(oid); for (ObjectReferenceType ort : objectType.getParentOrgRef()) { registerVertexIfNeeded(ort.getOid()); @@ -593,13 +539,13 @@ protected void registerObject(ObjectType objectType, boolean registerChildrenLin if (registerChildrenLinks) { // let's check for existing children List children = getOrgChildren(oid); - LOGGER.info("Registering children of {}: {} into memory graph", oid, children); + logger.info("Registering children of {}: {} into memory graph", oid, children); for (String child : children) { registerVertexIfNeeded(child); orgGraph.addEdge(child, oid); } } - LOGGER.info("Registration of {} done.", oid); + logger.info("Registration of {} done.", oid); } private void registerVertexIfNeeded(String oid) { @@ -626,7 +572,6 @@ private List getOrgChildren(String oid) { } } - protected void removeOrgStructure(OperationResult result) throws Exception { for (String rootOid : rootOids) { removeOrgStructure(rootOid, result); @@ -647,7 +592,7 @@ protected void removeOrgStructure(String nodeOid, OperationResult result) throws } catch (Exception e) { System.err.println("error while deleting " + nodeOid + ": " + e.getMessage()); } - LOGGER.trace("Org " + nodeOid + " was removed"); + logger.trace("Org " + nodeOid + " was removed"); } protected void removeUsersFromOrg(String nodeOid, OperationResult result) throws Exception { @@ -658,7 +603,7 @@ protected void removeUsersFromOrg(String nodeOid, OperationResult result) throws for (PrismObject user : users) { try { repositoryService.deleteObject(UserType.class, user.getOid(), result); - LOGGER.trace("User " + user.getOid() + " was removed"); + logger.trace("User " + user.getOid() + " was removed"); } catch (Exception e) { System.err.println("error while deleting " + user.getOid() + ": " + e.getMessage()); } @@ -670,7 +615,7 @@ protected void randomRemoveOrgStructure(OperationResult result) throws Exception long totalTime = 0; List vertices = new ArrayList<>(getVertices()); while (!vertices.isEmpty()) { - int i = (int) Math.floor(vertices.size()*Math.random()); + int i = (int) Math.floor(vertices.size() * Math.random()); String oid = vertices.get(i); Class clazz = oid.startsWith("o") ? OrgType.class : UserType.class; // hack! try { @@ -683,11 +628,11 @@ protected void randomRemoveOrgStructure(OperationResult result) throws Exception } orgGraph.removeVertex(oid); vertices.remove(oid); - if (count%getConfiguration().getDeletionsToClosureTest() == 0) { + if (count % getConfiguration().getDeletionsToClosureTest() == 0) { checkClosure(getVertices()); } } - System.out.println(count + " objects deleted in avg time " + ((float) totalTime/count) + " ms (net)"); + System.out.println(count + " objects deleted in avg time " + ((float) totalTime / count) + " ms (net)"); } protected PrismObject createUser(List parentOids, String oidPrefix) @@ -746,18 +691,15 @@ protected PrismObject createOrg(List parentOids, String oidPref protected String createOid(String oidPrefix) { String oid = StringUtils.rightPad(oidPrefix, 31, '.'); - StringBuilder sb = new StringBuilder(); - sb.append(oid.substring(0, 7)); - sb.append('-'); - sb.append(oid.substring(7, 11)); - sb.append('-'); - sb.append(oid.substring(11, 15)); - sb.append('-'); - sb.append(oid.substring(15, 19)); - sb.append('-'); - sb.append(oid.substring(19, 31)); - - return sb.toString(); + return oid.substring(0, 7) + + '-' + + oid.substring(7, 11) + + '-' + + oid.substring(11, 15) + + '-' + + oid.substring(15, 19) + + '-' + + oid.substring(19, 31); } protected PolyStringType createPolyString(String orig) { @@ -796,7 +738,7 @@ protected long getNetDuration() { protected void _test100LoadOrgStructure() throws Exception { OperationResult opResult = new OperationResult("===[ test100LoadOrgStructure ]==="); - LOGGER.info("Start."); + logger.info("Start."); long start = System.currentTimeMillis(); loadOrgStructure(0, null, "", opResult); @@ -852,7 +794,6 @@ protected void _test190AddLink(String childOid, String parentOid) throws Excepti //checkClosure(orgGraph.vertexSet()); } - protected void _test195RemoveLink(String childOid, String parentOid) throws Exception { OperationResult opResult = new OperationResult("===[ test195RemoveLink ]==="); @@ -941,9 +882,9 @@ protected void _test200AddRemoveLinks(boolean useReplace) throws Exception { if (totalRounds > 0) { System.out.println("Avg time for an arbitrary link removal: " + ((double) totalTimeLinkRemovals / totalRounds) + " ms"); System.out.println("Avg time for an arbitrary link re-addition: " + ((double) totalTimeLinkAdditions / totalRounds) + " ms"); - LOGGER.info("==================================================="); - LOGGER.info("Statistics for org link removal/addition:"); - stat.dump(LOGGER, baseHelper.getConfiguration().getHibernateDialect(), allOrgCreated.size(), allUsersCreated.size(), closureSize, "AddRemoveLinks"); + logger.info("==================================================="); + logger.info("Statistics for org link removal/addition:"); + stat.dump(logger, baseHelper.getConfiguration().getHibernateDialect(), allOrgCreated.size(), allUsersCreated.size(), closureSize, "AddRemoveLinks"); } } @@ -995,9 +936,9 @@ protected void _test300AddRemoveOrgs() throws Exception { if (totalRounds > 0) { System.out.println("Avg time for an arbitrary node removal: " + ((double) totalTimeNodeRemovals / totalRounds) + " ms"); System.out.println("Avg time for an arbitrary node re-addition: " + ((double) totalTimeNodeAdditions / totalRounds) + " ms"); - LOGGER.info("==================================================="); - LOGGER.info("Statistics for org node removal/addition:"); - stat.dump(LOGGER, baseHelper.getConfiguration().getHibernateDialect(), allOrgCreated.size(), allUsersCreated.size(), closureSize, "AddRemoveOrgs"); + logger.info("==================================================="); + logger.info("Statistics for org node removal/addition:"); + stat.dump(logger, baseHelper.getConfiguration().getHibernateDialect(), allOrgCreated.size(), allUsersCreated.size(), closureSize, "AddRemoveOrgs"); } } @@ -1028,6 +969,7 @@ protected void _test390CyclePrevention() throws Exception { checkClosure(getVertices()); } + @UnusedTestElement protected void _test400UnloadOrgStructure() throws Exception { OperationResult opResult = new OperationResult("===[ unloadOrgStruct ]==="); long start = System.currentTimeMillis(); @@ -1039,7 +981,7 @@ protected void _test400UnloadOrgStructure() throws Exception { System.out.println("OrgClosure table has " + q.list().get(0) + " rows"); } - LOGGER.info("Finish."); + logger.info("Finish."); } protected void _test410RandomUnloadOrgStructure() throws Exception { @@ -1055,13 +997,11 @@ protected void _test410RandomUnloadOrgStructure() throws Exception { assertEquals("Closure is not empty", "0", count.toString()); } - LOGGER.info("Finish."); + logger.info("Finish."); } protected void info(String s) { System.out.println(s); - LOGGER.info(s); + logger.info(s); } - - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/OrgClosureConcurrencyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/OrgClosureConcurrencyTest.java index 20c2ffc9e94..302818e5b80 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/OrgClosureConcurrencyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/closure/OrgClosureConcurrencyTest.java @@ -7,46 +7,38 @@ package com.evolveum.midpoint.repo.sql.closure; +import static com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.Edge; + +import java.util.*; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import static com.evolveum.midpoint.repo.sql.helpers.OrgClosureManager.Edge; /** * @author mederly */ -@ContextConfiguration(locations = {"../../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class OrgClosureConcurrencyTest extends AbstractOrgClosureTest { - private static final Trace LOGGER = TraceManager.getTrace(OrgClosureConcurrencyTest.class); - - private static final int[] ORG_CHILDREN_IN_LEVEL = { 5, 3, 3, 3 }; + private static final int[] ORG_CHILDREN_IN_LEVEL = { 5, 3, 3, 3 }; private static final int[] USER_CHILDREN_IN_LEVEL = null; - private static final int[] PARENTS_IN_LEVEL = { 0, 2, 2, 3 }; - private static final int[] LINK_ROUNDS_FOR_LEVELS = { 0, 15, 20, 30 }; -// private static final int[] NODE_ROUNDS_FOR_LEVELS = { 3, 3, 3, 3 }; // small number of deletes + private static final int[] PARENTS_IN_LEVEL = { 0, 2, 2, 3 }; + private static final int[] LINK_ROUNDS_FOR_LEVELS = { 0, 15, 20, 30 }; + // private static final int[] NODE_ROUNDS_FOR_LEVELS = { 3, 3, 3, 3 }; // small number of deletes // private static final int[] NODE_ROUNDS_FOR_LEVELS = { 3, 15, 20, 30 }; // average number of deletes - private static final int[] NODE_ROUNDS_FOR_LEVELS = { 5, 15, 45, 100 }; // large number of deletes + private static final int[] NODE_ROUNDS_FOR_LEVELS = { 5, 15, 45, 100 }; // large number of deletes public static final int THREADS = 4; /* @@ -59,7 +51,7 @@ public class OrgClosureConcurrencyTest extends AbstractOrgClosureTest { * * Dunno why. Let's use a timeout of 30 minutes so that the tests would not loop indefinitely. */ - public static final long TIMEOUT = 1800L*1000L; + public static final long TIMEOUT = 1800L * 1000L; // very small scenario // private static final int[] ORG_CHILDREN_IN_LEVEL = { 1, 2, 1 }; @@ -87,18 +79,41 @@ public OrgClosureTestConfiguration getConfiguration() { return configuration; } - @Test public void test100LoadOrgStructure() throws Exception { _test100LoadOrgStructure(); } - @Test public void test150CheckClosure() throws Exception { _test150CheckClosure(); } - @Test public void test200AddRemoveLinksSeq() throws Exception { _test200AddRemoveLinksMT(false); } - @Test public void test201AddRemoveLinksRandom() throws Exception { _test200AddRemoveLinksMT(true); } - @Test public void test300AddRemoveNodesSeq() throws Exception { _test300AddRemoveNodesMT(false); } - @Test public void test301AddRemoveNodesRandom() throws Exception { _test300AddRemoveNodesMT(true); } + @Test + public void test100LoadOrgStructure() throws Exception { + _test100LoadOrgStructure(); + } + + @Test + public void test150CheckClosure() throws Exception { + _test150CheckClosure(); + } + + @Test + public void test200AddRemoveLinksSeq() throws Exception { + _test200AddRemoveLinksMT(false); + } + + @Test + public void test201AddRemoveLinksRandom() throws Exception { + _test200AddRemoveLinksMT(true); + } + + @Test + public void test300AddRemoveNodesSeq() throws Exception { + _test300AddRemoveNodesMT(false); + } + + @Test + public void test301AddRemoveNodesRandom() throws Exception { + _test300AddRemoveNodesMT(true); + } /** * We randomly select a set of links to be removed. * Then we remove them, using a given set of threads. * After all threads are done, we will check the closure table consistency. - * + *

* And after that, we will do the reverse, re-adding all the links previously removed. * In the end, we again check the consistency. */ @@ -107,10 +122,10 @@ protected void _test200AddRemoveLinksMT(final boolean random) throws Exception { info("test200AddRemoveLinks starting with random = " + random); - final Set edgesToRemove = Collections.synchronizedSet(new HashSet()); - final Set edgesToAdd = Collections.synchronizedSet(new HashSet()); + final Set edgesToRemove = Collections.synchronizedSet(new HashSet<>()); + final Set edgesToAdd = Collections.synchronizedSet(new HashSet<>()); - final List exceptions = Collections.synchronizedList(new ArrayList()); + final List exceptions = Collections.synchronizedList(new ArrayList<>()); // parentRef link removal + addition for (int level = 0; level < getConfiguration().getLinkRoundsForLevel().length; level++) { @@ -149,7 +164,7 @@ protected void _test200AddRemoveLinksMT(final boolean random) throws Exception { int numberOfRunners = THREADS; info("Edges to remove/add (" + edgesToRemove.size() + ": " + edgesToRemove); info("Number of runners: " + numberOfRunners); - final List runners = Collections.synchronizedList(new ArrayList()); + final List runners = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < numberOfRunners; i++) { Runnable runnable = new Runnable() { @@ -161,7 +176,7 @@ public void run() { if (edge == null) { break; } - LOGGER.info("Removing {}", edge); + logger.info("Removing {}", edge); removeEdge(edge); int remaining; synchronized (OrgClosureConcurrencyTest.this) { @@ -206,7 +221,7 @@ public void run() { if (edge == null) { break; } - LOGGER.info("Adding {}", edge); + logger.info("Adding {}", edge); addEdge(edge); int remaining; synchronized (OrgClosureConcurrencyTest.this) { @@ -247,7 +262,7 @@ private void waitForRunnersCompletion(List runners) throws InterruptedEx long start = System.currentTimeMillis(); while (!runners.isEmpty()) { Thread.sleep(100); // primitive way of waiting - if (System.currentTimeMillis()-start > TIMEOUT) { + if (System.currentTimeMillis() - start > TIMEOUT) { throw new AssertionError("Test is running for too long. Probably caused by a locked-up thread. Runners = " + runners); } } @@ -276,7 +291,7 @@ private void removeEdge(Edge edge) throws ObjectAlreadyExistsException, ObjectNo .createModificationDelete(OrgType.class, OrgType.F_PARENT_ORG_REF, parentOrgRef.asReferenceValue()); modifications.add(removeParent); repositoryService.modifyObject(OrgType.class, edge.getDescendant(), modifications, new OperationResult("dummy")); - synchronized(this) { + synchronized (this) { orgGraph.removeEdge(edge.getDescendant(), edge.getAncestor()); } } @@ -290,7 +305,7 @@ private void addEdge(Edge edge) throws ObjectAlreadyExistsException, ObjectNotFo parentOrgRef.asReferenceValue()); modifications.add(itemDelta); repositoryService.modifyObject(OrgType.class, edge.getDescendant(), modifications, new OperationResult("dummy")); - synchronized(this) { + synchronized (this) { orgGraph.addEdge(edge.getDescendant(), edge.getAncestor()); } } @@ -300,10 +315,10 @@ protected void _test300AddRemoveNodesMT(final boolean random) throws Exception { info("test300AddRemoveNodes starting with random = " + random); - final Set nodesToRemove = Collections.synchronizedSet(new HashSet()); - final Set nodesToAdd = Collections.synchronizedSet(new HashSet()); + final Set nodesToRemove = Collections.synchronizedSet(new HashSet<>()); + final Set nodesToAdd = Collections.synchronizedSet(new HashSet<>()); - final List exceptions = Collections.synchronizedList(new ArrayList()); + final List exceptions = Collections.synchronizedList(new ArrayList<>()); for (int level = 0; level < getConfiguration().getNodeRoundsForLevel().length; level++) { int rounds = getConfiguration().getNodeRoundsForLevel()[level]; @@ -312,7 +327,7 @@ protected void _test300AddRemoveNodesMT(final boolean random) throws Exception { } int numberOfRunners = THREADS; - final List runners = Collections.synchronizedList(new ArrayList()); + final List runners = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < numberOfRunners; i++) { Runnable runnable = new Runnable() { @@ -324,7 +339,7 @@ public void run() { if (objectType == null) { break; } - LOGGER.info("Removing {}", objectType); + logger.info("Removing {}", objectType); int remaining; try { removeObject(objectType); @@ -377,7 +392,7 @@ public void run() { if (objectType == null) { break; } - LOGGER.info("Adding {}", objectType); + logger.info("Adding {}", objectType); try { addObject(objectType.clone()); // rebuildGraph(); @@ -426,7 +441,7 @@ private void rebuildGraph() { OperationResult result = new OperationResult("dummy"); info("Graph before rebuilding: " + orgGraph.vertexSet().size() + " vertices, " + orgGraph.edgeSet().size() + " edges"); orgGraph.removeAllVertices(new HashSet<>(orgGraph.vertexSet())); - List objects = null; + List objects; try { objects = (List) repositoryService.searchObjects(OrgType.class, null, null, result); } catch (SchemaException e) { @@ -449,13 +464,13 @@ private void rebuildGraph() { } } } - info("Graph after rebuilding: "+orgGraph.vertexSet().size()+" vertices, "+orgGraph.edgeSet().size()+" edges"); + info("Graph after rebuilding: " + orgGraph.vertexSet().size() + " vertices, " + orgGraph.edgeSet().size() + " edges"); } private void generateNodesAtOneLevel(Set nodesToRemove, Set nodesToAdd, - Class clazz, - int rounds, List candidateOids, - OperationResult opResult) throws ObjectNotFoundException, SchemaException { + Class clazz, + int rounds, List candidateOids, + OperationResult opResult) throws ObjectNotFoundException, SchemaException { if (candidateOids.isEmpty()) { return; } @@ -482,7 +497,7 @@ private void generateNodesAtOneLevel(Set nodesToRemove, Set childOrg = repositoryService.getObject(OrgType.class, childOid, null, opResult); childOrg.asObjectable().getParentOrgRef().clear(); - LOGGER.info("+++ adding object with 'overwrite' option +++"); + logger.info("+++ adding object with 'overwrite' option +++"); repositoryService.addObject(childOrg, RepoAddOptions.createOverwrite(), opResult); orgGraph.removeEdge(childOid, parentOid); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractHigherUnitTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractHigherUnitTest.java index 61c43773027..5a62ddd2eaa 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractHigherUnitTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractHigherUnitTest.java @@ -504,10 +504,6 @@ protected void displaySkip(String testName) { TestUtil.displaySkip(testName); } - protected void display(String str) { - IntegrationTestTools.display(str); - } - public static void display(String message, SearchResultEntry response) { IntegrationTestTools.display(message, response); } @@ -553,11 +549,7 @@ public static void display(String title, List elements) { } public static void display(String title, DebugDumpable dumpable) { - IntegrationTestTools.display(title, dumpable); - } - - public static void display(String title, String value) { - IntegrationTestTools.display(title, value); + PrismTestUtil.display(title, dumpable); } public static void display(String title, Object value) { diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 06708a49342..c4dcdab15ca 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -120,7 +120,8 @@ * @author Radovan Semancik */ @Listeners({ CurrentTestResultHolder.class }) -public abstract class AbstractIntegrationTest extends AbstractSpringTest { +public abstract class AbstractIntegrationTest extends AbstractSpringTest + implements OperationResultTestMixin { protected static final String USER_ADMINISTRATOR_USERNAME = "administrator"; @@ -290,7 +291,7 @@ public void finishTestContext(ITestResult testResult) { MidpointTestContextWithTask context = MidpointTestContextWithTask.get(); MidpointTestContextWithTask.destroy(); // let's destroy it before anything else in this method - displayDefaultTestFooter(context.getTestName(), testResult); + displayTestFooter(context.getTestName(), testResult); Task task = context.getTask(); if (task != null) { @@ -397,20 +398,6 @@ protected OperationResult createSubresult(String subresultSuffix) { return getTestOperationResult().createSubresult(getTestNameShort() + "." + subresultSuffix); } - /** - * Creates new {@link OperationResult} with name equal to {@link #contextName()}. - */ - protected OperationResult createOperationalResult() { - return new OperationResult(contextName()); - } - - /** - * Creates new {@link OperationResult} with name prefixed by {@link #contextName()}. - */ - protected OperationResult createOperationalResult(String nameSuffix) { - return new OperationResult(contextName() + "." + nameSuffix); - } - /** * Returns default {@link OperationResult} for pre-created test-method-scoped {@link Task}. * This result can be freely used in test for some "main scope", it is not asserted in any @@ -1824,12 +1811,12 @@ protected PrismObject parseObject(File file) throws Sc return prismContext.parseObject(file); } - protected void displayCleanup(String testName) { - TestUtil.displayCleanup(testName); + protected void displayCleanup() { + TestUtil.displayCleanup(getTestNameShort()); } - protected void displaySkip(String testName) { - TestUtil.displaySkip(testName); + protected void displaySkip() { + TestUtil.displaySkip(getTestNameShort()); } /** @@ -1841,10 +1828,6 @@ protected void displayHEREHERE() { IntegrationTestTools.display("HEREHERE"); } - protected void display(String str) { - IntegrationTestTools.display(str); - } - public static void display(String message, SearchResultEntry response) { IntegrationTestTools.display(message, response); } @@ -1889,16 +1872,12 @@ public static void display(String title, List elements) { IntegrationTestTools.display(title, elements); } - public static void display(String title, DebugDumpable dumpable) { - IntegrationTestTools.display(title, dumpable); + public void display(String title, DebugDumpable dumpable) { + PrismTestUtil.display(title, dumpable); } - public static void display(String title, String value) { - IntegrationTestTools.display(title, value); - } - - public static void display(String title, Object value) { - IntegrationTestTools.display(title, value); + public void display(String title, Object value) { + PrismTestUtil.display(title, value); } public static void display(String title, Containerable value) { @@ -1983,8 +1962,10 @@ protected void setTracing(Task task, TracingProfileType profile) { task.setTracingProfile(profile); } - protected static final String TEST_METHOD_TRACING_FILENAME_PATTERN = "trace %{timestamp} %{operationNameShort} %{milliseconds}"; - protected static final String DEFAULT_TRACING_FILENAME_PATTERN = "trace %{timestamp} %{testNameShort} %{operationNameShort} %{focusName} %{milliseconds}"; + protected static final String TEST_METHOD_TRACING_FILENAME_PATTERN = + "trace %{timestamp} %{operationNameShort} %{milliseconds}"; + protected static final String DEFAULT_TRACING_FILENAME_PATTERN = + "trace %{timestamp} %{testNameShort} %{operationNameShort} %{focusName} %{milliseconds}"; protected TracingProfileType createModelLoggingTracingProfile() { return createDefaultTracingProfile() diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java index 55e39b0dce6..27804f85812 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java @@ -52,6 +52,7 @@ import com.evolveum.midpoint.schema.util.*; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.DebugUtil; @@ -231,6 +232,7 @@ public static void assertEqualsCollection(String message, Collection expe } } + @UnusedTestElement public static void assertEqualsCollection(String message, Collection expectedValues, T[] actualValues) { assertEqualsCollection(message, expectedValues, Arrays.asList(actualValues)); } @@ -239,6 +241,7 @@ public static void assertEqualsCollection(String message, T[] expectedValues assertEqualsCollection(message, Arrays.asList(expectedValues), actualValues); } + @UnusedTestElement public static String getIcfsNameAttribute(PrismObject shadow) { return getIcfsNameAttribute(shadow.asObjectable()); } @@ -262,6 +265,7 @@ public static void assertSecondaryIdentifier(PrismObject repoShadow, assertEquals("Wrong secondary indetifier in " + repoShadow, value, getSecondaryIdentifier(repoShadow)); } + @UnusedTestElement public static void assertIcfsNameAttribute(ShadowType repoShadow, String value) { assertAttribute(repoShadow, SchemaTestConstants.ICFS_NAME, value); } @@ -495,13 +499,6 @@ public static void display(String title, List elements) { } } - public static void display(String title, DebugDumpable dumpable) { - println(OBJECT_TITLE_OUT_PREFIX + title); - println(dumpable == null ? "null" : dumpable.debugDump(1)); - LOGGER.debug(OBJECT_TITLE_LOG_PREFIX + title + "\n" - + (dumpable == null ? "null" : dumpable.debugDump(1))); - } - public static void display(String title, String value) { println(OBJECT_TITLE_OUT_PREFIX + title); println(value); @@ -601,6 +598,7 @@ public static void assertSearchResultNames(SearchResultLi PrismAsserts.assertSets("Unexpected search result", matchingRule, names, expectedNames); } + @UnusedTestElement public static void assertSearchResultNames( SearchResultList> resultList, String... expectedNames) { List names = new ArrayList<>(expectedNames.length); @@ -642,6 +640,7 @@ public static ObjectQuery createAllShadowsQuery( return createAllShadowsQuery(resourceType, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), objectClassLocalName), prismContext); } + @UnusedTestElement public static void checkAccountShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker checker, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkAccountShadow(shadowType, resourceType, repositoryService, checker, null, prismContext, parentResult); @@ -654,6 +653,7 @@ public static void checkAccountShadow(ShadowType shadowType, ResourceType resour shadowType.getObjectClass()); } + @UnusedTestElement public static void checkEntitlementShadow(ShadowType shadowType, ResourceType resourceType, RepositoryService repositoryService, ObjectChecker checker, String objectClassLocalName, PrismContext prismContext, OperationResult parentResult) throws SchemaException { checkEntitlementShadow(shadowType, resourceType, repositoryService, checker, objectClassLocalName, null, prismContext, parentResult); @@ -796,6 +796,7 @@ public static boolean hasInMessageRecursive(Throwable e, String substring) { return false; } + @UnusedTestElement public static void assertNotInMessageRecursive(Throwable e, String substring) { assert !e.getMessage().contains(substring) : "The substring '" + substring + "' was found in the message of exception " + e + ": " + e.getMessage(); if (e.getCause() != null) { @@ -1066,7 +1067,7 @@ public static void assertConnectorSchemaSanity(ConnectorType conn, PrismContext public static void assertConnectorSchemaSanity(PrismSchema schema, String connectorDescription, boolean expectConnIdSchema) { assertNotNull("Cannot parse connector schema of " + connectorDescription, schema); assertFalse("Empty connector schema in " + connectorDescription, schema.isEmpty()); - display("Parsed connector schema of " + connectorDescription, schema); + PrismTestUtil.display("Parsed connector schema of " + connectorDescription, schema); // Local schema namespace is used here. PrismContainerDefinition configurationDefinition = @@ -1158,6 +1159,7 @@ public static void assertHasProtectedString(String message, } } + @UnusedTestElement public static boolean isSilentConsole() { return silentConsole; } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/DummyObjectAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/DummyObjectAsserter.java index 820b8582e7c..2d85303ca2b 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/DummyObjectAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/DummyObjectAsserter.java @@ -16,7 +16,7 @@ import org.testng.AssertJUnit; import com.evolveum.icf.dummy.resource.DummyObject; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; /** * @author semancik @@ -116,7 +116,7 @@ public DummyObjectAsserter display() { } public DummyObjectAsserter display(String message) { - IntegrationTestTools.display(message, dummyObject); + PrismTestUtil.display(message, dummyObject); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/ObjectReferenceAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/ObjectReferenceAsserter.java index b3c5016a569..b3f3b3cadf8 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/ObjectReferenceAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/ObjectReferenceAsserter.java @@ -14,8 +14,8 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; @@ -115,7 +115,7 @@ public ObjectReferenceAsserter display() { } public ObjectReferenceAsserter display(String message) { - IntegrationTestTools.display(message, refVal); + PrismTestUtil.display(message, refVal); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ComplexTypeDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ComplexTypeDefinitionAsserter.java index 2481f6494d5..f9c82655f8a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ComplexTypeDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ComplexTypeDefinitionAsserter.java @@ -11,7 +11,7 @@ import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.ComplexTypeDefinition; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -63,7 +63,7 @@ public ComplexTypeDefinitionAsserter display() { } public ComplexTypeDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, complexTypeDefinition); + PrismTestUtil.display(message, complexTypeDefinition); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/DeltaSetTripleAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/DeltaSetTripleAsserter.java index 4b9808b3201..2f61aa28b08 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/DeltaSetTripleAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/DeltaSetTripleAsserter.java @@ -12,7 +12,7 @@ import java.util.Collection; import com.evolveum.midpoint.prism.delta.DeltaSetTriple; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; /** @@ -112,7 +112,7 @@ public DeltaSetTripleAsserter display() { } public DeltaSetTripleAsserter display(String message) { - IntegrationTestTools.display(message, triple); + PrismTestUtil.display(message, triple); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectDeltaAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectDeltaAsserter.java index 3a3a3cbf90a..41b2cd19de5 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectDeltaAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectDeltaAsserter.java @@ -15,7 +15,7 @@ import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.test.asserter.ContainerDeltaAsserter; import com.evolveum.midpoint.test.asserter.PropertyDeltaAsserter; @@ -114,7 +114,7 @@ public ObjectDeltaAsserter display() { } public ObjectDeltaAsserter display(String message) { - IntegrationTestTools.display(message, delta); + PrismTestUtil.display(message, delta); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectFilterAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectFilterAsserter.java index 28184e7fd78..67c12feace2 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectFilterAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/ObjectFilterAsserter.java @@ -11,9 +11,10 @@ import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.TypeFilter; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.AbstractAsserter; + import org.testng.AssertJUnit; import javax.xml.namespace.QName; @@ -127,7 +128,7 @@ public ObjectFilterAsserter display() { } public ObjectFilterAsserter display(String message) { - IntegrationTestTools.display(message, filter); + PrismTestUtil.display(message, filter); return this; } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PolyStringAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PolyStringAsserter.java index cbc11cb0a88..8e72644c2bf 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PolyStringAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PolyStringAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.test.asserter.prism; import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -93,7 +93,7 @@ public PolyStringAsserter display() { } public PolyStringAsserter display(String message) { - IntegrationTestTools.display(message, polystring); + PrismTestUtil.display(message, polystring); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismContainerDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismContainerDefinitionAsserter.java index 794b8b89751..3121bab1502 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismContainerDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismContainerDefinitionAsserter.java @@ -14,7 +14,7 @@ import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.util.PrettyPrinter; @@ -75,7 +75,7 @@ public PrismContainerDefinitionAsserter display() { } public PrismContainerDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, getDefinition()); + PrismTestUtil.display(message, getDefinition()); return this; } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismDefinitionAsserter.java index 0b66c5563b0..1f5838f9b4f 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismDefinitionAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.test.asserter.prism; import com.evolveum.midpoint.prism.Definition; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; /** @@ -46,7 +46,7 @@ public PrismDefinitionAsserter display() { } public PrismDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, definition); + PrismTestUtil.display(message, definition); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismPropertyDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismPropertyDefinitionAsserter.java index a0ebe5d3f1d..bbe20e0a3ba 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismPropertyDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismPropertyDefinitionAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.test.asserter.prism; import com.evolveum.midpoint.prism.PrismPropertyDefinition; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.util.PrettyPrinter; /** @@ -45,7 +45,7 @@ public PrismPropertyDefinitionAsserter display() { } public PrismPropertyDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, getDefinition()); + PrismTestUtil.display(message, getDefinition()); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismSchemaAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismSchemaAsserter.java index 96def842f01..eb14f6a2b4a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismSchemaAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/prism/PrismSchemaAsserter.java @@ -7,7 +7,7 @@ package com.evolveum.midpoint.test.asserter.prism; import com.evolveum.midpoint.prism.schema.PrismSchema; -import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.test.asserter.AbstractAsserter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; @@ -58,7 +58,7 @@ public PrismSchemaAsserter display() { } public PrismSchemaAsserter display(String message) { - IntegrationTestTools.display(message, schema); + PrismTestUtil.display(message, schema); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ObjectClassComplexTypeDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ObjectClassComplexTypeDefinitionAsserter.java index fe20f66195b..d97e84d923c 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ObjectClassComplexTypeDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ObjectClassComplexTypeDefinitionAsserter.java @@ -8,8 +8,8 @@ import javax.xml.namespace.QName; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.prism.ComplexTypeDefinitionAsserter; import com.evolveum.midpoint.util.PrettyPrinter; @@ -61,7 +61,7 @@ public ObjectClassComplexTypeDefinitionAsserter display() { } public ObjectClassComplexTypeDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, getComplexTypeDefinition()); + PrismTestUtil.display(message, getComplexTypeDefinition()); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/RefinedResourceSchemaAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/RefinedResourceSchemaAsserter.java index bfbb13d2a50..7fe41f2576c 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/RefinedResourceSchemaAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/RefinedResourceSchemaAsserter.java @@ -10,8 +10,8 @@ import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.prism.PrismSchemaAsserter; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; @@ -101,7 +101,7 @@ public RefinedResourceSchemaAsserter display() { } public RefinedResourceSchemaAsserter display(String message) { - IntegrationTestTools.display(message, getSchema()); + PrismTestUtil.display(message, getSchema()); return this; } } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ResourceAttributeDefinitionAsserter.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ResourceAttributeDefinitionAsserter.java index 7c3febda6ec..7fd8e2fe4c9 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ResourceAttributeDefinitionAsserter.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/asserter/refinedschema/ResourceAttributeDefinitionAsserter.java @@ -6,9 +6,9 @@ */ package com.evolveum.midpoint.test.asserter.refinedschema; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.asserter.prism.PrismPropertyDefinitionAsserter; import com.evolveum.midpoint.util.PrettyPrinter; @@ -93,7 +93,7 @@ public ResourceAttributeDefinitionAsserter display() { } public ResourceAttributeDefinitionAsserter display(String message) { - IntegrationTestTools.display(message, getDefinition()); + PrismTestUtil.display(message, getDefinition()); return this; } } diff --git a/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/MidPointPrincipalManagerMock.java b/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/MidPointPrincipalManagerMock.java index 153b593f26a..d27d19fd447 100644 --- a/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/MidPointPrincipalManagerMock.java +++ b/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/MidPointPrincipalManagerMock.java @@ -59,22 +59,19 @@ public class MidPointPrincipalManagerMock implements MidPointPrincipalManager, U private static final Trace LOGGER = TraceManager.getTrace(MidPointPrincipalManagerMock.class); - @Autowired(required = true) + @Autowired private transient RepositoryService repositoryService; - @Autowired(required = true) + @Autowired private ActivationComputer activationComputer; - @Autowired(required = true) - private Clock clock; - - @Autowired(required = true) + @Autowired private PrismContext prismContext; @Override public MidPointPrincipal getPrincipal(String username, Class clazz) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(OPERATION_GET_PRINCIPAL); - PrismObject focus = null; + PrismObject focus; try { focus = findByUsername(username, clazz, result); } catch (ObjectNotFoundException ex) { diff --git a/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/TestEmpty.java b/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/TestEmpty.java index 13767a27c58..7e3ae8d1c66 100644 --- a/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/TestEmpty.java +++ b/repo/security-impl/src/test/java/com/evolveum/midpoint/security/impl/TestEmpty.java @@ -11,23 +11,18 @@ import java.io.File; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Listeners; import org.testng.annotations.Test; -import com.evolveum.midpoint.common.Clock; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.AbstractIntegrationTest; import com.evolveum.midpoint.test.util.MidPointTestConstants; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -54,14 +49,9 @@ public class TestEmpty extends AbstractIntegrationTest { protected static final String USER_JACK_USERNAME = "jack"; protected static final String USER_JACK_PASSWORD = "deadmentellnotales"; - private static final Trace LOGGER = TraceManager.getTrace(TestEmpty.class); - - @Autowired(required=true) + @Autowired private MidPointPrincipalManagerMock userProfileService; - @Autowired(required = true) - private Clock clock; - /* (non-Javadoc) * @see com.evolveum.midpoint.test.AbstractIntegrationTest#initSystem(com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @@ -80,8 +70,6 @@ public void test000Sanity() throws Exception { @Test public void test020GuiProfiledPrincipalManagerMockUsername() throws Exception { - final String TEST_NAME = "test020GuiProfiledPrincipalManagerMockUsername"; - MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); assertPrincipalJack(principal); } @@ -91,9 +79,7 @@ private void assertPrincipalJack(MidPointPrincipal principal) { assertEquals("Bad principal name", USER_JACK_USERNAME, principal.getName().getOrig()); assertEquals("Bad principal name", USER_JACK_USERNAME, principal.getUsername()); FocusType user = principal.getFocus(); - assertNotNull("No user in principal",user); + assertNotNull("No user in principal", user); assertEquals("Bad name in user in principal", USER_JACK_USERNAME, user.getName().getOrig()); } - - } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index af26ad6c483..6176259d5a3 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -10,7 +10,6 @@ import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; import java.io.File; @@ -37,6 +36,7 @@ import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.CommonException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; @@ -344,4 +344,12 @@ private Set getCachingProfiles(Task task) { TaskExecutionEnvironmentType env = task.getExecutionEnvironment(); return env != null ? new HashSet<>(env.getCachingProfile()) : Collections.emptySet(); } + + protected void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + protected void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/CleanupTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/CleanupTest.java index c605c2f01b6..92d958308c2 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/CleanupTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/CleanupTest.java @@ -7,8 +7,6 @@ package com.evolveum.midpoint.task.quartzimpl; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.io.File; import java.util.Calendar; import java.util.Date; @@ -31,7 +29,6 @@ import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.sql.type.XMLGregorianCalendarType; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.test.util.AbstractSpringTest; import com.evolveum.midpoint.xml.ns._public.common.common_3.CleanupPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; @@ -40,7 +37,7 @@ */ @ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -public class CleanupTest extends AbstractSpringTest { +public class CleanupTest extends AbstractTaskManagerTest { public static final File FOLDER_BASIC = new File("./src/test/resources/basic"); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestMiscellaneous.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestMiscellaneous.java index c315ffc22fa..454990e5a28 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestMiscellaneous.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestMiscellaneous.java @@ -10,7 +10,6 @@ import static java.util.Collections.singletonList; import static org.testng.AssertJUnit.assertEquals; -import static com.evolveum.midpoint.prism.util.PrismTestUtil.display; import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; import java.io.IOException; diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java index 734ac14fcd1..0d6b0ec0fa2 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java @@ -6,26 +6,23 @@ */ package com.evolveum.midpoint.task.quartzimpl; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.quartzimpl.work.WorkStateManager; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import org.jetbrains.annotations.NotNull; +import static java.util.Collections.singleton; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.List; +import javax.annotation.PostConstruct; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; -import javax.annotation.PostConstruct; -import java.util.List; - -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static java.util.Collections.singleton; -import static org.testng.AssertJUnit.assertEquals; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.quartzimpl.work.WorkStateManager; +import com.evolveum.midpoint.util.DebugUtil; /** * Tests task handlers for workers creation and for task partitioning. @@ -33,63 +30,34 @@ * @author mederly */ -@ContextConfiguration(locations = {"classpath:ctx-task-test.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestPartitioning extends AbstractTaskManagerTest { - private static final Trace LOGGER = TraceManager.getTrace(TestPartitioning.class); public static final long DEFAULT_SLEEP_INTERVAL = 250L; public static final long DEFAULT_TIMEOUT = 30000L; @Autowired private WorkStateManager workStateManager; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/partitioning/task-" + testNumber(testName) + "-" + subId + ".xml"; + @PostConstruct + public void initialize() throws Exception { + super.initialize(); + workStateManager.setFreeBucketWaitIntervalOverride(1000L); + DebugUtil.setPrettyPrintBeansAs(PrismContext.LANG_YAML); } - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private static String taskFilename(String testName, String subId) { + return "src/test/resources/partitioning/task-" + testNumber(testName) + "-" + subId + ".xml"; } private static String taskOid(String testName, String subId) { return "44444444-2222-2222-8888-" + testNumber(testName) + subId + "00000000"; } - private static String taskOid(String test) { - return taskOid(test, "0"); - } - private static String testNumber(String test) { return test.substring(4, 7); } - @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); - } - - @NotNull - protected String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); - } - - @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); - } - - @NotNull - protected String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); - } - - @PostConstruct - public void initialize() throws Exception { - super.initialize(); - workStateManager.setFreeBucketWaitIntervalOverride(1000L); - DebugUtil.setPrettyPrintBeansAs(PrismContext.LANG_YAML); - } - @Test public void test000Integrity() { AssertJUnit.assertNotNull(repositoryService); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java index ce1d4ab6745..dceefebe0d5 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java @@ -6,6 +6,28 @@ */ package com.evolveum.midpoint.task.quartzimpl; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.task.quartzimpl.TaskTestUtil.createExtensionDelta; +import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import javax.annotation.PostConstruct; + +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; +import org.quartz.SchedulerException; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; +import org.xml.sax.SAXException; + import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.PropertyDelta; @@ -31,30 +53,7 @@ import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.quartz.JobExecutionContext; -import org.quartz.JobKey; -import org.quartz.SchedulerException; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.xml.sax.SAXException; - -import javax.annotation.PostConstruct; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import static com.evolveum.midpoint.task.quartzimpl.TaskTestUtil.createExtensionDelta; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; -import static org.testng.AssertJUnit.*; /** * @author Radovan Semancik @@ -64,8 +63,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { - private static final Trace LOGGER = TraceManager.getTrace(TestQuartzTaskManagerContract.class); - private static final String TASK_OWNER_FILENAME = "src/test/resources/basic/owner.xml"; private static final String TASK_OWNER2_FILENAME = "src/test/resources/basic/owner2.xml"; private static final String TASK_OWNER2_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; @@ -116,7 +113,7 @@ public void test003GetProgress() throws Exception { addObjectFromFile(taskFilename(TEST_NAME)); - LOGGER.trace("Retrieving the task and getting its progress..."); + logger.trace("Retrieving the task and getting its progress..."); TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress()); @@ -161,7 +158,7 @@ public void test004aTaskBigProperty() throws Exception { System.out.println("1st round: Task = " + task.debugDump()); - LOGGER.trace("Retrieving the task and comparing its properties..."); + logger.trace("Retrieving the task and comparing its properties..."); Task task001 = getTask(taskOid(TEST_NAME), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); @@ -222,7 +219,7 @@ public void test004bTaskBigProperty() throws Exception { System.out.println("1st round: Task = " + task.debugDump()); - LOGGER.trace("Retrieving the task and comparing its properties..."); + logger.trace("Retrieving the task and comparing its properties..."); Task task001 = getTask(taskOid(TEST_NAME), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); @@ -354,14 +351,14 @@ public void test004TaskProperties() throws Exception { objectReferenceType.setOid(objectOid); task.setObjectRef(objectReferenceType); - LOGGER.trace("Saving modifications..."); + logger.trace("Saving modifications..."); task.flushPendingModifications(result); - LOGGER.trace("Retrieving the task (second time) and comparing its properties..."); + logger.trace("Retrieving the task (second time) and comparing its properties..."); Task task001 = getTask(taskOid(TEST_NAME), result); - LOGGER.trace("Task from repo: " + task001.debugDump()); + logger.trace("Task from repo: " + task001.debugDump()); AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding()); PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName()); // AssertJUnit.assertEquals(newname, task001.getName()); @@ -443,11 +440,11 @@ public void test005Single() throws Exception { // Add single task. This will get picked by task scanner and executed addObjectFromFile(taskFilename(TEST_NAME)); - LOGGER.trace("Retrieving the task..."); + logger.trace("Retrieving the task..."); TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); AssertJUnit.assertNotNull(task); - LOGGER.trace("Task retrieval OK."); + logger.trace("Task retrieval OK."); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this @@ -455,7 +452,7 @@ public void test005Single() throws Exception { waitForTaskClose(taskOid(TEST_NAME), result, 10000, 1000); - LOGGER.info("... done"); + logger.info("... done"); // Check task status @@ -1034,7 +1031,7 @@ public void test016WaitForSubtasks() throws Exception { secondPrerequisiteTask.addDependent(rootTask.getTaskIdentifier()); taskManager.switchToBackground(secondPrerequisiteTask, result); - LOGGER.info("Starting waiting for child/prerequisite tasks"); + logger.info("Starting waiting for child/prerequisite tasks"); rootTask.startWaitingForTasksImmediate(result); firstChildTask.refresh(result); @@ -1054,7 +1051,7 @@ public void test016WaitForSubtasks() throws Exception { assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (count differs)", 1, deps.size()); assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (value differs)", rootTask.getOid(), deps.get(0).getOid()); - LOGGER.info("Resuming suspended child/prerequisite tasks"); + logger.info("Resuming suspended child/prerequisite tasks"); taskManager.resumeTask(secondChildTask, result); taskManager.resumeTask(secondPrerequisiteTask, result); @@ -1214,7 +1211,7 @@ public void test021DeleteTaskTree() throws Exception { taskManager.resumeTask(childTask2, result); parentTask.startWaitingForTasksImmediate(result); - LOGGER.info("Deleting task {} and its subtasks", parentTask); + logger.info("Deleting task {} and its subtasks", parentTask); taskManager.suspendAndDeleteTasks(Collections.singletonList(parentTask.getOid()), 2000L, true, result); @@ -1565,14 +1562,14 @@ private void checkLeftover(ArrayList leftovers, String testNumber, Strin t = getTask(oid, result); } catch (ObjectNotFoundException e) { // this is OK, test probably did not start - LOGGER.info("Check leftovers: Task " + oid + " does not exist."); + logger.info("Check leftovers: Task " + oid + " does not exist."); return; } - LOGGER.info("Check leftovers: Task " + oid + " state: " + t.getExecutionStatus()); + logger.info("Check leftovers: Task " + oid + " state: " + t.getExecutionStatus()); if (t.getExecutionStatus() == TaskExecutionStatus.RUNNABLE) { - LOGGER.info("Leftover task: {}", t); + logger.info("Leftover task: {}", t); leftovers.add(t.getOid()); } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java index e863887be25..446e9ca3d10 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java @@ -6,6 +6,22 @@ */ package com.evolveum.midpoint.task.quartzimpl; +import static java.util.Collections.singletonList; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertTrue; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import javax.annotation.PostConstruct; + +import org.jetbrains.annotations.NotNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; @@ -17,26 +33,7 @@ import com.evolveum.midpoint.task.quartzimpl.work.segmentation.WorkSegmentationStrategyFactory; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.jetbrains.annotations.NotNull; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import javax.annotation.PostConstruct; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; - -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static java.util.Collections.singletonList; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; /** * Low level tests of work bucket strategies. @@ -44,12 +41,10 @@ * @author mederly */ -@ContextConfiguration(locations = {"classpath:ctx-task-test.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestWorkBucketStrategies extends AbstractTaskManagerTest { - private static final Trace LOGGER = TraceManager.getTrace(TestWorkBucketStrategies.class); - @Autowired private WorkStateManager workStateManager; @Autowired private WorkSegmentationStrategyFactory strategyFactory; diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java index 8413a7e0918..85ecd80bf57 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java @@ -6,6 +6,25 @@ */ package com.evolveum.midpoint.task.quartzimpl; +import static java.util.Collections.singleton; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.util.TaskWorkStateTypeUtil.sortBucketsBySequentialNumber; +import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import javax.annotation.PostConstruct; + +import org.jetbrains.annotations.NotNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; @@ -14,30 +33,11 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.task.quartzimpl.work.WorkStateManager; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.Holder; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.jetbrains.annotations.NotNull; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import javax.annotation.PostConstruct; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static com.evolveum.midpoint.schema.util.TaskWorkStateTypeUtil.sortBucketsBySequentialNumber; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; -import static java.util.Collections.singleton; -import static org.testng.AssertJUnit.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.WorkBucketStateType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.WorkBucketType; /** * Tests basic features of work state management: @@ -45,18 +45,16 @@ * - allocation, completion, release of buckets * - allocation of buckets when some workers are suspended * - basic propagation of buckets into bucket-aware task handler - * + *

* Both in coordinator-worker and standalone tasks. * * @author mederly */ -@ContextConfiguration(locations = {"classpath:ctx-task-test.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestWorkDistribution extends AbstractTaskManagerTest { - private static final Trace LOGGER = TraceManager.getTrace(TestWorkDistribution.class); - public static final long DEFAULT_TIMEOUT = 30000L; @Autowired private WorkStateManager workStateManager; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java index 900752738bf..d6cff6bce65 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java @@ -69,8 +69,6 @@ import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.aspect.ProfilingDataManager; import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.*; @@ -82,8 +80,6 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapTest extends AbstractModelIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(AbstractLdapTest.class); - public static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml"); public static final String SYSTEM_CONFIGURATION_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value(); @@ -125,7 +121,7 @@ public abstract class AbstractLdapTest extends AbstractModelIntegrationTest { protected static final QName ASSOCIATION_GROUP_NAME = new QName(MidPointConstants.NS_RI, "group"); - @Autowired(required = true) + @Autowired protected MatchingRuleRegistry matchingRuleRegistry; @Autowired @@ -294,6 +290,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti modelService.postInit(initResult); + // TODO what now? config is unused // to get profiling facilities (until better API is available) // LoggingConfigurationManager.configure( // ProfilingConfigurationManager.checkSystemProfilingConfiguration(config), @@ -685,7 +682,7 @@ protected List ldapSearch(UserLdapConnectionConfig config, LdapNetworkCon } protected List ldapSearch(LdapNetworkConnection connection, String baseDn, String filter, SearchScope scope, String... attributes) throws LdapException, CursorException { - LOGGER.trace("LDAP search base={}, filter={}, scope={}, attributes={}", + logger.trace("LDAP search base={}, filter={}, scope={}, attributes={}", baseDn, filter, scope, attributes); SearchRequest searchRequest = new SearchRequestImpl(); @@ -733,11 +730,11 @@ protected void assertLdapPassword(UserLdapConnectionConfig config, Entry entry, int foundEntries = 0; while (cursor.next()) { Entry entryFound = cursor.get(); - LOGGER.trace("Search-after-auth found: {}", entryFound); + logger.trace("Search-after-auth found: {}", entryFound); foundEntries++; } cursor.close(); - LOGGER.debug("Search-after-auth found {} entries", foundEntries); + logger.debug("Search-after-auth found {} entries", foundEntries); ldapDisconnect(conn); if (foundEntries != 1) { throw new SecurityException("Cannot read my own entry (" + entry.getDn() + ")"); @@ -778,7 +775,7 @@ protected Entry addLdapGroup(String cn, String description, String... memberDns) throws LdapException, IOException { LdapNetworkConnection connection = ldapConnect(); Entry entry = createGroupEntry(cn, description, memberDns); - LOGGER.trace("Adding LDAP entry:\n{}", entry); + logger.trace("Adding LDAP entry:\n{}", entry); connection.add(entry); display("Added LDAP group:" + entry); ldapDisconnect(connection); @@ -886,7 +883,7 @@ protected LdapNetworkConnection ldapConnect(UserLdapConnectionConfig config) thr config.setBindDn(getLdapBindDn()); config.setBindPassword(getLdapBindPassword()); } - LOGGER.trace("LDAP connect to {}:{} as {}", + logger.trace("LDAP connect to {}:{} as {}", config.getLdapHost(), config.getLdapPort(), config.getBindDn()); if (useSsl()) { @@ -912,7 +909,7 @@ public X509Certificate[] getAcceptedIssuers() { if (!connected) { AssertJUnit.fail("Cannot connect to LDAP server " + config.getLdapHost() + ":" + config.getLdapPort()); } - LOGGER.trace("LDAP connected to {}:{}, executing bind as {}", + logger.trace("LDAP connected to {}:{}, executing bind as {}", config.getLdapHost(), config.getLdapPort(), config.getBindDn()); BindRequest bindRequest = new BindRequestImpl(); bindRequest.setDn(new Dn(config.getBindDn())); @@ -923,13 +920,13 @@ public X509Certificate[] getAcceptedIssuers() { ldapDisconnect(connection); throw new SecurityException("Bind as " + config.getBindDn() + " failed: " + bindResponse.getLdapResult().getDiagnosticMessage() + " (" + bindResponse.getLdapResult().getResultCode() + ")"); } - LOGGER.trace("LDAP connected to {}:{}, bound as {}", + logger.trace("LDAP connected to {}:{}, bound as {}", config.getLdapHost(), config.getLdapPort(), config.getBindDn()); return connection; } protected void ldapDisconnect(LdapNetworkConnection connection) throws IOException { - LOGGER.trace("LDAP disconnect {}", connection); + logger.trace("LDAP disconnect {}", connection); connection.close(); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java index 6f920af9c4f..97fc539e0d3 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java @@ -138,7 +138,7 @@ protected void assertActivationCapability(ActivationCapabilityType activationCap @Override protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { - OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName() + ".assertSyncToken"); + OperationResult result = createOperationResult(); Task task = taskManager.getTask(syncTaskOid, result); result.computeStatus(); TestUtil.assertSuccess(result); @@ -147,7 +147,7 @@ protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, l assertNotNull("No sync token in " + task, syncTokenProperty); String syncToken = syncTokenProperty.getRealValue(); assertNotNull("No sync token in " + task, syncToken); - IntegrationTestTools.display("Sync token", syncToken); + display("Sync token", syncToken); GeneralizedTime syncTokenGt; try { diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainRunAsTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainRunAsTest.java index 85a4a6635e2..f3c43c3459f 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainRunAsTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainRunAsTest.java @@ -20,9 +20,8 @@ /** * @author semancik - * */ -@Listeners({com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class}) +@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public abstract class AbstractAdLdapMultidomainRunAsTest extends AbstractAdLdapMultidomainTest { @Override @@ -40,11 +39,11 @@ protected void assertAdditionalCapabilities(List nativeCapabilities) { @Test @Override public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws Exception { - final String TEST_NAME = "test222ModifyUserBarbossaPasswordSelfServicePassword1Again"; - testModifyUserBarbossaPasswordSelfServiceFailure(TEST_NAME, USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); + testModifyUserBarbossaPasswordSelfServiceFailure( + USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); assertUserAfter(USER_BARBOSSA_OID) - .assertPassword(USER_BARBOSSA_PASSWORD_AD_1); + .assertPassword(USER_BARBOSSA_PASSWORD_AD_1); } /** @@ -56,10 +55,8 @@ public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws @Test @Override public void test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain() throws Exception { - final String TEST_NAME = "test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain"; - testModifyUserBarbossaPasswordSelfServiceFailure(TEST_NAME, USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); - - + testModifyUserBarbossaPasswordSelfServiceFailure( + USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); } /** @@ -74,10 +71,9 @@ public void test228ModifyUserBarbossaPasswordSelfServiceDesynchronized() throws // preconditions assertUserBefore(USER_BARBOSSA_OID) - .assertPassword(USER_BARBOSSA_PASSWORD_AD_1); + .assertPassword(USER_BARBOSSA_PASSWORD_AD_1); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_2); - login(USER_BARBOSSA_USERNAME); Task task = getTestTask(); @@ -100,11 +96,11 @@ public void test228ModifyUserBarbossaPasswordSelfServiceDesynchronized() throws assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); assertUserAfter(USER_BARBOSSA_OID) - .assertPassword(USER_BARBOSSA_PASSWORD_AD_3) - .singleLink() + .assertPassword(USER_BARBOSSA_PASSWORD_AD_3) + .singleLink() .resolveTarget() - .pendingOperations() - .assertNone(); + .pendingOperations() + .assertNone(); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_2); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java index 8dbd98711f8..96fdf4fbcc2 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java @@ -71,7 +71,8 @@ * @author semancik */ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) -public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest { +public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest + implements AdTestMixin { protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap-multidomain"); @@ -272,15 +273,15 @@ private UserLdapConnectionConfig getSubLdapConnectionConfig() { protected abstract String getReconciliationTaskOid(); protected String getLdapConnectorClassName() { - return AdUtils.AD_CONNECTOR_TYPE; + return AD_CONNECTOR_TYPE; } @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - binaryAttributeDetector.addBinaryAttribute(AdUtils.ATTRIBUTE_OBJECT_GUID_NAME); - binaryAttributeDetector.addBinaryAttribute(AdUtils.ATTRIBUTE_UNICODE_PWD_NAME); + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_OBJECT_GUID_NAME); + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_UNICODE_PWD_NAME); // Users repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); @@ -321,9 +322,9 @@ public void test000Sanity() throws Exception { @Override public void test020Schema() throws Exception { // IntegrationTestTools.displayXml("Resource XML", resource); - accountObjectClassDefinition = AdUtils.assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); - AdUtils.assertAdRefinedSchema(resource, getAccountObjectClass()); - AdUtils.assertExchangeSchema(resource, getAccountObjectClass(), prismContext); + accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); + assertAdRefinedSchema(resource, getAccountObjectClass()); + assertExchangeSchema(resource, getAccountObjectClass(), prismContext); ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); assertEquals("Unexpected number of schema definitions (limited by generation constraints)", 5, resourceSchema.getDefinitions().size()); @@ -493,7 +494,7 @@ public void test110GetJack() throws Exception { rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - long startOfTestMsTimestamp = AdUtils.getWin32Filetime(System.currentTimeMillis()); + long startOfTestMsTimestamp = getWin32Filetime(System.currentTimeMillis()); // WHEN when(); @@ -766,13 +767,13 @@ public void test200AssignAccountBarbossa() throws Exception { assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); assertEquals("Wrong ICFS UID", - AdUtils.formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), accountBarbossaIcfUid); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); // MID-4624 ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); @@ -795,7 +796,7 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { ObjectDelta delta = prismContext.deltaFactory().object() .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, AdUtils.ATTRIBUTE_TITLE_NAME); + QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_TITLE_NAME); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); @@ -810,9 +811,9 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { assertSuccess(result); Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, AdUtils.ATTRIBUTE_TITLE_NAME, "Captain"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertAttribute(entry, ATTRIBUTE_TITLE_NAME, "Captain"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -846,8 +847,8 @@ public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exce Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "showInAdvancedViewOnly", "TRUE"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -885,8 +886,8 @@ public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Except Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "showInAdvancedViewOnly", "FALSE"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -910,7 +911,7 @@ public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception ObjectDelta delta = prismContext.deltaFactory().object() .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, AdUtils.ATTRIBUTE_PROXY_ADDRESSES_NAME); + QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_PROXY_ADDRESSES_NAME); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); assertNotNull("No definition for attribute " + attrQName, attrDef); PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationAddProperty( @@ -926,9 +927,9 @@ public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception assertSuccess(result); Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, AdUtils.ATTRIBUTE_PROXY_ADDRESSES_NAME, PROXY_ADDRES_ADDR_UPCASE); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertAttribute(entry, ATTRIBUTE_PROXY_ADDRESSES_NAME, PROXY_ADDRES_ADDR_UPCASE); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -940,8 +941,8 @@ public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception @Test public void test220ModifyUserBarbossaPasswordSelfServicePassword1() throws Exception { - final String TEST_NAME = "test220ModifyUserBarbossaPasswordSelfServicePassword1"; - testModifyUserBarbossaPasswordSelfServiceSuccess(TEST_NAME, USER_BARBOSSA_PASSWORD, USER_BARBOSSA_PASSWORD_AD_1); + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD, USER_BARBOSSA_PASSWORD_AD_1); } /** @@ -951,8 +952,8 @@ public void test220ModifyUserBarbossaPasswordSelfServicePassword1() throws Excep */ @Test public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws Exception { - final String TEST_NAME = "test222ModifyUserBarbossaPasswordSelfServicePassword1Again"; - testModifyUserBarbossaPasswordSelfServiceSuccess(TEST_NAME, USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); } /** @@ -961,8 +962,8 @@ public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws */ @Test public void test224ModifyUserBarbossaPasswordSelfServicePassword2() throws Exception { - final String TEST_NAME = "test220ModifyUserBarbossaPasswordSelfServicePassword1"; - testModifyUserBarbossaPasswordSelfServiceSuccess(TEST_NAME, USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_2); + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_2); } /** @@ -972,11 +973,11 @@ public void test224ModifyUserBarbossaPasswordSelfServicePassword2() throws Excep */ @Test public void test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain() throws Exception { - final String TEST_NAME = "test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain"; - testModifyUserBarbossaPasswordSelfServiceSuccess(TEST_NAME, USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); } - protected void testModifyUserBarbossaPasswordSelfServiceSuccess(final String TEST_NAME, String oldPassword, String newPassword) throws Exception { + protected void testModifyUserBarbossaPasswordSelfServiceSuccess(String oldPassword, String newPassword) throws Exception { // GIVEN assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, oldPassword); @@ -1005,7 +1006,8 @@ protected void testModifyUserBarbossaPasswordSelfServiceSuccess(final String TES assertLdapConnectorInstances(2); } - protected void testModifyUserBarbossaPasswordSelfServiceFailure(final String TEST_NAME, String oldPassword, String newPassword) throws Exception { + protected void testModifyUserBarbossaPasswordSelfServiceFailure( + String oldPassword, String newPassword) throws Exception { // GIVEN login(USER_BARBOSSA_USERNAME); @@ -1178,8 +1180,8 @@ protected PrismObject assertBarbossaEnabled(String ldapPassword) throw Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, AdUtils.ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "FALSE"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "FALSE"); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); @@ -1200,9 +1202,9 @@ private void assertBarbossaDisabled(String password) throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("disabled Barbossa entry", entry); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - assertAttribute(entry, AdUtils.ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "TRUE"); + assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "TRUE"); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); @@ -1244,7 +1246,7 @@ public void test250AssignGuybrushPirates() throws Exception { Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); display("Entry", entry); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); assertLdapGroupMember(entry, GROUP_PIRATES_NAME); @@ -1285,7 +1287,7 @@ public void test255ModifyUserGuybrushPassword() throws Exception { Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); display("Guybrush entry after", entry); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); try { assertLdapPassword(null, entry, USER_GUYBRUSH_PASSWORD_123); @@ -1317,7 +1319,7 @@ public void test260EnableGyubrush() throws Exception { assertAdministrativeStatus(user, ActivationStatusType.ENABLED); Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); @@ -1533,8 +1535,8 @@ public void test500AddOrgMeleeIsland() throws Exception { assertSuccess(result); orgMeleeIslandOid = org.getOid(); - Entry entryGroup = assertLdapGroup(GROUP_MELEE_ISLAND_NAME); - Entry entryOu = assertLdapOrg(GROUP_MELEE_ISLAND_NAME); + assertLdapGroup(GROUP_MELEE_ISLAND_NAME); + assertLdapOrg(GROUP_MELEE_ISLAND_NAME); org = getObject(OrgType.class, orgMeleeIslandOid); groupMeleeIslandOid = getLinkRefOid(org, getResourceOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); @@ -1618,15 +1620,13 @@ public void test515AddOrgGroupMeleeIslandPirates() throws Exception { roleMeleeIslandPiratesOid = role.getOid(); // TODO: assert LDAP object - Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); PrismObject roleAfter = getObject(RoleType.class, roleMeleeIslandPiratesOid); display("Role after", roleAfter); groupMeleeIslandPiratesOid = getSingleLinkOid(roleAfter); PrismObject shadow = getShadowModel(groupMeleeIslandPiratesOid); display("Shadow (model)", shadow); - -// assertLdapConnectorInstances(2); } /** @@ -1660,13 +1660,13 @@ public void test520RenameMeleeIsland() throws Exception { PrismObject shadowOu = getShadowModel(ouMeleeIslandOid); display("Shadow: ou (model)", shadowOu); - Entry groupEntry = assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); + assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - Entry entryOu = assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); + assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); - Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); + assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); Entry entryGuybrush = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); @@ -1733,9 +1733,9 @@ public void test524GetMeleeIslandPirates() throws Exception { display("Shadow after", shadow); assertNotNull(shadow); - Entry groupEntry = assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); + assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - Entry entryOu = assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); + assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); display("Melee org", entryOrgGroup); @@ -1840,12 +1840,12 @@ public void test600AssignAccountSubman() throws Exception { assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); assertEquals("Wrong ICFS UID", - AdUtils.formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), accountBarbossaIcfUid); assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, USER_SUBMAN_PASSWORD); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); // MID-4624 ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); @@ -1876,7 +1876,7 @@ public void test610ModifyUserSubmanTitle() throws Exception { Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); display("Sub entry", entry); assertAttribute(entry, "title", "Underdog"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); PrismObject user = getUser(USER_SUBMAN_OID); String shadowOid = getSingleLinkOid(user); @@ -1905,7 +1905,7 @@ public void test620ModifyUserSubmanPassword() throws Exception { Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); assertAttribute(entry, "title", "Underdog"); assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, "SuB.321"); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); PrismObject user = getUser(USER_SUBMAN_OID); String shadowOid = getSingleLinkOid(user); @@ -1936,7 +1936,7 @@ public void test630DisableUserSubman() throws Exception { assertAdministrativeStatus(user, ActivationStatusType.DISABLED); Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); @@ -1972,7 +1972,7 @@ public void test639EnableUserSubman() throws Exception { assertAdministrativeStatus(user, ActivationStatusType.ENABLED); Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); @@ -2077,10 +2077,10 @@ public void test700AssignAccountSubmarineAndModify() throws Exception { assertNotNull("No identifier in " + shadow, accountIcfUid); assertEquals("Wrong ICFS UID", - AdUtils.formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), accountIcfUid); - assertAttribute(entry, AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); } @Test @@ -2131,20 +2131,20 @@ protected void assertAccountShadow(PrismObject shadow, String dn) th String primaryId = primaryIdAttr.getRealValue(); assertTrue("Unexpected chars in primary ID: '" + primaryId + "'", primaryId.matches("[a-z0-9\\-]+")); - ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, AdUtils.ATTRIBUTE_OBJECT_SID_NAME)); + ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); assertNotNull("No SID in " + shadow, objectSidAttr); display("SID of " + dn + ": " + objectSidAttr); } - protected void assertSid(PrismObject shadow, String expectedSid) throws SchemaException { - ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, AdUtils.ATTRIBUTE_OBJECT_SID_NAME)); + protected void assertSid(PrismObject shadow, String expectedSid) { + ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); assertNotNull("No SID in " + shadow, objectSidAttr); display("SID of " + shadow + ": " + objectSidAttr); assertEquals("Wrong SID in " + shadow, expectedSid, objectSidAttr.getRealValue()); } private void assertObjectCategory(PrismObject shadow, String expectedObjectCategory) { - ResourceAttribute objectCategoryAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, AdUtils.ATTRIBUTE_OBJECT_CATEGORY_NAME)); + ResourceAttribute objectCategoryAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_CATEGORY_NAME)); assertNotNull("No objectCategory in " + shadow, objectCategoryAttr); display("objectCategory of " + shadow + ": " + objectCategoryAttr); assertEquals("Wrong objectCategory in " + shadow, expectedObjectCategory, objectCategoryAttr.getRealValue()); @@ -2154,14 +2154,14 @@ private void assertObjectCategory(PrismObject shadow, String expecte protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { Entry entry = searchLdapAccount("(cn=" + cn + ")"); assertAttribute(entry, "cn", cn); - assertAttribute(entry, AdUtils.ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); + assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); return entry; } protected Entry assertLdapSubAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { Entry entry = searchLdapAccount(getSubLdapConnectionConfig(), "(cn=" + cn + ")"); assertAttribute(entry, "cn", cn); - assertAttribute(entry, AdUtils.ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); + assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); return entry; } @@ -2264,7 +2264,7 @@ protected void assertLdapPassword(String uid, String password) { protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(AdUtils.ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), + ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), prismContext); return query; } @@ -2274,12 +2274,12 @@ protected Entry createAccountEntry(String uid, String cn, String givenName, Stri byte[] password = encodePassword("Secret.123"); Entry entry = new DefaultEntry(toAccountDn(uid, cn), "objectclass", getLdapAccountObjectClass(), - AdUtils.ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, "cn", cn, "givenName", givenName, "sn", sn, - AdUtils.ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", - AdUtils.ATTRIBUTE_UNICODE_PWD_NAME, password); + ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", + ATTRIBUTE_UNICODE_PWD_NAME, password); return entry; } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapRawTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapRawTest.java index 82cfcd54ba8..81c3137a5a1 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapRawTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapRawTest.java @@ -6,7 +6,7 @@ */ package com.evolveum.midpoint.testing.conntest.ad; -import static com.evolveum.midpoint.testing.conntest.ad.AdUtils.*; +import static com.evolveum.midpoint.testing.conntest.ad.AdTestMixin.*; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java index 7a95d721c5d..d99100da1ba 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java @@ -10,7 +10,6 @@ import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE; -import static com.evolveum.midpoint.testing.conntest.ad.AdUtils.*; import java.io.File; import java.io.IOException; @@ -71,7 +70,8 @@ * @author semancik */ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) -public abstract class AbstractAdLdapTest extends AbstractLdapSynchronizationTest { +public abstract class AbstractAdLdapTest extends AbstractLdapSynchronizationTest + implements AdTestMixin { protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap"); @@ -199,7 +199,7 @@ protected boolean isGroupMemberMandatory() { } protected String getLdapConnectorClassName() { - return AdUtils.AD_CONNECTOR_TYPE; + return AdTestMixin.AD_CONNECTOR_TYPE; } @Override @@ -224,7 +224,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test000Sanity() throws Exception { super.test000Sanity(); - assertLdapPassword(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); + assertLdapPasswordByFullName(ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME)); cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME)); cleanupDelete(toAccountDn(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME)); @@ -235,7 +235,7 @@ public void test000Sanity() throws Exception { @Test @Override public void test020Schema() throws Exception { - accountObjectClassDefinition = AdUtils.assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); + accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); assertLdapConnectorInstances(1); } @@ -590,10 +590,10 @@ public void test200AssignAccountBarbossa() throws Exception { assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); assertEquals("Wrong ICFS UID", - AdUtils.formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), accountBarbossaIcfUid); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); @@ -730,7 +730,7 @@ public void test220ModifyUserBarbossaPassword() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_2); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_2); assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -762,7 +762,7 @@ public void test222ModifyUserBarbossaPasswordNational() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); PrismObject user = getUser(USER_BARBOSSA_OID); @@ -779,7 +779,7 @@ public void test230DisableUserBarbossa() throws Exception { OperationResult result = task.getResult(); // precondition - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); // WHEN when(); @@ -802,7 +802,7 @@ public void test230DisableUserBarbossa() throws Exception { assertAccountDisabled(shadow); try { - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); AssertJUnit.fail("Password authentication works, but it should fail"); } catch (SecurityException e) { // this is expected @@ -896,7 +896,7 @@ public void test255ModifyUserGuybrushPassword() throws Exception { assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); try { - assertLdapPassword(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); + assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); AssertJUnit.fail("Password authentication works, but it should fail"); } catch (SecurityException e) { // this is expected, account is disabled @@ -930,7 +930,7 @@ public void test260EnableGyubrush() throws Exception { PrismObject shadow = getObject(ShadowType.class, shadowOid); assertAccountEnabled(shadow); - assertLdapPassword(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); + assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); assertLdapConnectorInstances(2); } @@ -1089,7 +1089,7 @@ public void test500AddOrgMeleeIsland() throws Exception { TestUtil.assertSuccess(result); orgMeleeIslandOid = org.getOid(); - Entry entry = assertLdapGroup(GROUP_MELEE_ISLAND_NAME); + assertLdapGroup(GROUP_MELEE_ISLAND_NAME); org = getObject(OrgType.class, orgMeleeIslandOid); groupMeleeOid = getSingleLinkOid(org); @@ -1192,13 +1192,15 @@ protected Rdn toAccountRdn(String username, String fullName) { } } - protected void assertLdapPassword(String uid, String fullName, String password) throws LdapException, IOException, CursorException { + protected void assertLdapPasswordByFullName(String fullName, String password) + throws LdapException, IOException, CursorException { Entry entry = getLdapAccountByCn(fullName); assertLdapPassword(entry, password); } protected void assertLdapPassword(String uid, String password) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + throw new UnsupportedOperationException( + "Boom! Cannot do this here. This is bloody AD! We need full name!"); } protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { @@ -1228,9 +1230,9 @@ private byte[] encodePassword(String password) { } @Override - protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, - SchemaException { - OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName() + ".assertSyncToken"); + protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) + throws ObjectNotFoundException, SchemaException { + OperationResult result = createOperationResult("assertStepSyncToken"); Task task = taskManager.getTask(syncTaskOid, result); PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); assertNotNull("No sync token", syncTokenProperty); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdUtils.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java similarity index 75% rename from testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdUtils.java rename to testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java index 9f0251af1ac..cda56d91940 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdUtils.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import javax.xml.namespace.QName; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; @@ -18,42 +16,42 @@ import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; +import com.evolveum.midpoint.tools.testng.MidpointTestMixin; import com.evolveum.midpoint.util.DOMUtil; +import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -/** - * @author semancik - */ -public class AdUtils { +public interface AdTestMixin extends MidpointTestMixin { - public static final String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; - public static final String ATTRIBUTE_OBJECT_SID_NAME = "objectSid"; - public static final String ATTRIBUTE_OBJECT_CATEGORY_NAME = "objectCategory"; - public static final String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; - public static final String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; - public static final QName ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME); - public static final String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; - public static final String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; - public static final QName ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); - public static final String ATTRIBUTE_TITLE_NAME = "title"; - public static final String ATTRIBUTE_PROXY_ADDRESSES_NAME = "proxyAddresses"; + String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; + String ATTRIBUTE_OBJECT_SID_NAME = "objectSid"; + String ATTRIBUTE_OBJECT_CATEGORY_NAME = "objectCategory"; + String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; + String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; + QName ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME); + String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; + String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; + QName ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); + String ATTRIBUTE_TITLE_NAME = "title"; + String ATTRIBUTE_PROXY_ADDRESSES_NAME = "proxyAddresses"; - public static final QName OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME = new QName(MidPointConstants.NS_RI, "msExchBaseClass"); + QName OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME = new QName(MidPointConstants.NS_RI, "msExchBaseClass"); - public static final String AD_CONNECTOR_TYPE = "com.evolveum.polygon.connector.ldap.ad.AdLdapConnector"; + String AD_CONNECTOR_TYPE = "com.evolveum.polygon.connector.ldap.ad.AdLdapConnector"; /** * Returns dashed GUID notation formatted from simple hex-encoded binary. *

* E.g. "2f01c06bb1d0414e9a69dd3841a13506" -> "6bc0012f-d0b1-4e41-9a69-dd3841a13506" */ - public static String formatGuidToDashedNotation(String hexValue) { + default String formatGuidToDashedNotation(String hexValue) { if (hexValue == null) { return null; } @@ -73,21 +71,26 @@ public static String formatGuidToDashedNotation(String hexValue) { + hexValue.substring(20, 32); } - public static ObjectClassComplexTypeDefinition assertAdResourceSchema(PrismObject resource, QName accountObjectClass, PrismContext prismContext) throws SchemaException { + default ObjectClassComplexTypeDefinition assertAdResourceSchema( + PrismObject resource, QName accountObjectClass, PrismContext prismContext) + throws SchemaException { ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); display("Resource schema", resourceSchema); ResourceTypeUtil.validateSchema(resourceSchema, resource); return assertAdSchema(resource, accountObjectClass); } - public static ObjectClassComplexTypeDefinition assertAdResourceSchemaLongTimestamp(PrismObject resource, QName accountObjectClass, PrismContext prismContext) throws SchemaException { + default ObjectClassComplexTypeDefinition assertAdResourceSchemaLongTimestamp( + PrismObject resource, QName accountObjectClass, PrismContext prismContext) + throws SchemaException { ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); display("Resource schema", resourceSchema); ResourceTypeUtil.validateSchema(resourceSchema, resource); return assertAdSchemaLongTimestamp(resource, accountObjectClass); } - public static ObjectClassComplexTypeDefinition assertAdRefinedSchema(PrismObject resource, QName accountObjectClass) throws SchemaException { + default ObjectClassComplexTypeDefinition assertAdRefinedSchema( + PrismObject resource, QName accountObjectClass) throws SchemaException { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); display("Refined schema", refinedSchema); RefinedResourceSchemaImpl.validateRefinedSchema(refinedSchema, resource); @@ -95,19 +98,22 @@ public static ObjectClassComplexTypeDefinition assertAdRefinedSchema(PrismObject } // Assumes string timestamp - public static ObjectClassComplexTypeDefinition assertAdSchema(PrismObject resource, QName accountObjectClass) throws SchemaException { + default ObjectClassComplexTypeDefinition assertAdSchema( + PrismObject resource, QName accountObjectClass) throws SchemaException { ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); - ResourceAttributeDefinition createTimestampDef = accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); - PrismAsserts.assertDefinition(createTimestampDef, new QName(MidPointConstants.NS_RI, "createTimeStamp"), - DOMUtil.XSD_DATETIME, 0, 1); + ResourceAttributeDefinition createTimestampDef = + accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); + PrismAsserts.assertDefinition(createTimestampDef, + new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); assertTrue("createTimeStampDef read", createTimestampDef.canRead()); assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); - ResourceAttributeDefinition whenChangedDef = accountObjectClassDefinition.findAttributeDefinition("whenChanged"); - PrismAsserts.assertDefinition(whenChangedDef, new QName(MidPointConstants.NS_RI, "createTimeStamp"), - DOMUtil.XSD_DATETIME, 0, 1); + ResourceAttributeDefinition whenChangedDef = + accountObjectClassDefinition.findAttributeDefinition("whenChanged"); + PrismAsserts.assertDefinition(whenChangedDef, + new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); assertTrue("whenChanged read", whenChangedDef.canRead()); assertFalse("whenChanged modify", whenChangedDef.canModify()); assertFalse("whenChanged add", whenChangedDef.canAdd()); @@ -116,7 +122,8 @@ public static ObjectClassComplexTypeDefinition assertAdSchema(PrismObject resource, QName accountObjectClass) throws SchemaException { + default ObjectClassComplexTypeDefinition assertAdSchemaLongTimestamp( + PrismObject resource, QName accountObjectClass) throws SchemaException { ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); ResourceAttributeDefinition createTimestampDef = accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); @@ -129,7 +136,9 @@ public static ObjectClassComplexTypeDefinition assertAdSchemaLongTimestamp(Prism return accountObjectClassDefinition; } - private static ObjectClassComplexTypeDefinition assertAdSchemaBase(PrismObject resource, QName accountObjectClass) throws SchemaException { + // TODO after ditching JDK 8 + /*private*/ default ObjectClassComplexTypeDefinition assertAdSchemaBase( + PrismObject resource, QName accountObjectClass) throws SchemaException { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); display("Refined schema", refinedSchema); @@ -195,7 +204,7 @@ private static ObjectClassComplexTypeDefinition assertAdSchemaBase(PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { + default void assertExchangeSchema(PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); assertExchangeSchema(resourceSchema, accountObjectClassQName); @@ -204,7 +213,7 @@ public static void assertExchangeSchema(PrismObject resource, QNam assertExchangeSchema(refinedSchema, accountObjectClassQName); } - public static void assertExchangeSchema(ResourceSchema resourceSchema, QName accountObjectClassQName) { + default void assertExchangeSchema(ResourceSchema resourceSchema, QName accountObjectClassQName) { ObjectClassComplexTypeDefinition msExchBaseClassObjectClassDefinition = resourceSchema.findObjectClassDefinition(OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME); assertNotNull("No definition for object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME, msExchBaseClassObjectClassDefinition); display("Object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME + " def", msExchBaseClassObjectClassDefinition); @@ -226,8 +235,15 @@ public static void assertExchangeSchema(ResourceSchema resourceSchema, QName acc assertTrue("msExchHideFromAddressLists add", accountMsExchHideFromAddressListsDef.canAdd()); } - public static long getWin32Filetime(long millis) { + default long getWin32Filetime(long millis) { return (millis + 11644473600000L) * 10000L; } + default void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + default void display(String title, Object value) { + PrismTestUtil.display(title, value); + } } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java index b00c661b64e..e0f6e3ae8bf 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java @@ -14,8 +14,6 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.io.IOUtils; @@ -43,8 +41,6 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestGenericSynchronization extends AbstractModelIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestGenericSynchronization.class); - private static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml"); private static final String SYSTEM_CONFIGURATION_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value(); @@ -169,7 +165,7 @@ private int loadOpenDJ(int[] TREE_SIZE, int[] USER_COUNT, String dnSuffix, int c private void logCreateEntry(Entry entry) { if (logCreateEntry ) { System.out.println("Creating LDAP entry: " + entry.getDN()); - LOGGER.trace("Creating LDAP entry: {}", entry.getDN()); + logger.trace("Creating LDAP entry: {}", entry.getDN()); } } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java index c22cb9645a0..10d7400057f 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java @@ -107,7 +107,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { //end profiling ProfilingDataManager.getInstance().printMapAfterTest(); ProfilingDataManager.getInstance().stopProfilingAfterTest(); @@ -149,8 +149,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - assertUsers(NUM_INITIAL_USERS); } @@ -160,8 +158,6 @@ public void test000Sanity() throws Exception { */ @Test public void test200AssignRolePiratesToBarbossa() throws Exception { - final String TEST_NAME = "test200AssignRolePiratesToBarbossa"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -187,16 +183,13 @@ public void test200AssignRolePiratesToBarbossa() throws Exception { */ @Test public void test202AssignLdapAccountToGuybrush() throws Exception { - final String TEST_NAME = "test202AssignLdapAccountToGuybrush"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); byte[] photoIn = Files.readAllBytes(Paths.get(DOT_JPG_FILENAME)); display("Photo in", MiscUtil.binaryToHex(photoIn)); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_JPEG_PHOTO, task, result, - photoIn); + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_JPEG_PHOTO, task, result, photoIn); Collection> options = getOperationOptionsBuilder() .item(UserType.F_JPEG_PHOTO).retrieve() @@ -245,8 +238,6 @@ public void test202AssignLdapAccountToGuybrush() throws Exception { */ @Test public void test204AssignRolePiratesToGuybrush() throws Exception { - final String TEST_NAME = "test204AssignRolePiratesToGuybrush"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -275,8 +266,6 @@ public void test204AssignRolePiratesToGuybrush() throws Exception { @Test public void test400RenameLeChuckConflicting() throws Exception { - final String TEST_NAME = "test400RenameLeChuckConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -312,12 +301,8 @@ public void test400RenameLeChuckConflicting() throws Exception { @Test public void test800BigLdapSearch() throws Exception { - final String TEST_NAME = "test800BigLdapSearch"; - // GIVEN - assertUsers(NUM_INITIAL_USERS + 1); - loadLdapEntries("a", NUM_LDAP_ENTRIES); Task task = getTestTask(); @@ -356,10 +341,7 @@ public boolean handle(PrismObject shadow, OperationResult parentResu @Test public void test810BigImport() throws Exception { - final String TEST_NAME = "test810BigImport"; - // GIVEN - assertUsers(NUM_INITIAL_USERS + 1); loadLdapEntries("u", NUM_LDAP_ENTRIES); @@ -391,8 +373,6 @@ public void test810BigImport() throws Exception { @Test public void test820BigReconciliation() throws Exception { - final String TEST_NAME = "test820BigReconciliation"; - // GIVEN Task task = getTestTask(); @@ -428,10 +408,7 @@ public void test820BigReconciliation() throws Exception { @Test public void test900DeleteShadows() throws Exception { - final String TEST_NAME = "test900DeleteShadows"; - // GIVEN - Task task = getTestTask(); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); @@ -477,8 +454,6 @@ public void test900DeleteShadows() throws Exception { @Test public void test910DeleteAccounts() throws Exception { - final String TEST_NAME = "test910DeleteAccounts"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java index c5a89119d0f..33cfb69591d 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java @@ -7,11 +7,9 @@ package com.evolveum.midpoint.testing.longtest; - import static org.testng.AssertJUnit.assertEquals; import java.io.File; - import javax.xml.namespace.QName; import org.opends.server.types.Entry; @@ -39,9 +37,8 @@ * Mix of various tests for issues that are difficult to replicate using dummy resources. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-longtest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapComplex extends AbstractLongTest { @@ -85,7 +82,6 @@ public class TestLdapComplex extends AbstractLongTest { private static final String INTENT_SECURITY = "security"; private static final String OBJECTCLASS_USER_SECURITY_INFORMATION = "userSecurityInformation"; - protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -130,10 +126,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100BigImport() throws Exception { - final String TEST_NAME = "test100BigImport"; - // GIVEN - loadLdapEntries("u", NUM_LDAP_ENTRIES); Task task = getTestTask(); @@ -150,14 +143,14 @@ public void test100BigImport() throws Exception { OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000); + waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES * 2000); // THEN then(); int userCount = modelService.countObjects(UserType.class, null, null, task, result); display("Users", userCount); - assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+4, userCount); + assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES + 4, userCount); assertUser("u1", task, result); } @@ -171,8 +164,6 @@ private void assertUser(String name, Task task, OperationResult result) throws c @Test(enabled = false) public void test120BigReconciliation() throws Exception { - final String TEST_NAME = "test120BigReconciliation"; - // GIVEN Task task = getTestTask(); @@ -180,8 +171,6 @@ public void test120BigReconciliation() throws Exception { // WHEN when(); - //task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 2); - ResourceType resource = modelService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result).asObjectable(); reconciliationTaskHandler.launch(resource, new QName(RESOURCE_OPENDJ_NAMESPACE, "AccountObjectClass"), task, result); @@ -192,14 +181,14 @@ public void test120BigReconciliation() throws Exception { // OperationResult subresult = result.getLastSubresult(); // TestUtil.assertInProgress("reconciliation launch result", subresult); - waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000); + waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES * 2000); // THEN then(); int userCount = modelService.countObjects(UserType.class, null, null, task, result); display("Users", userCount); - assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+4, userCount); + assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES + 4, userCount); assertUser("u1", task, result); } @@ -209,8 +198,6 @@ public void test120BigReconciliation() throws Exception { */ @Test public void test500GuybrushAssignSecurity() throws Exception { - final String TEST_NAME = "test500GuybrushAssignSecurity"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -239,8 +226,6 @@ public void test500GuybrushAssignSecurity() throws Exception { */ @Test public void test502RuinGuybrushAccountAndReconcile() throws Exception { - final String TEST_NAME = "test502RuinGuybrushAccountAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -267,8 +252,4 @@ public void test502RuinGuybrushAccountAndReconcile() throws Exception { display("LDAP account after", entry); openDJController.assertHasObjectClass(entry, OBJECTCLASS_USER_SECURITY_INFORMATION); } - - private String toDn(String username) { - return "uid="+username+","+OPENDJ_PEOPLE_SUFFIX; - } } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java index b1a65c9d822..fc70ebf65f6 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java @@ -125,7 +125,7 @@ public void test100BigImportWithLinking() throws Exception { OperationResult result = task.getResult(); loadEntries("u"); - createUsers(new OperationResult("createUsers")); // we do not want to have all this in the task's result + createUsers(createOperationResult()); // we do not want to have all this in the task's result display("e0", findUserByUsername("e0")); diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestOrgHierarchy.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestOrgHierarchy.java index 02e149f5b9f..bb2f473517e 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestOrgHierarchy.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestOrgHierarchy.java @@ -6,15 +6,6 @@ */ package com.evolveum.midpoint.testing.longtest; -import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import java.io.File; import org.apache.commons.lang.ArrayUtils; @@ -23,23 +14,28 @@ import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; +import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + /** * @author lazyman */ -@ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-longtest-test-main.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestOrgHierarchy extends AbstractModelIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(TestOrgHierarchy.class); - - private static final File SYSTEM_CONFIGURATION_FILE = new File( COMMON_DIR, "system-configuration.xml"); + private static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml"); private static final String SYSTEM_CONFIGURATION_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value(); - private static final File USER_ADMINISTRATOR_FILENAME = new File( COMMON_DIR, "user-administrator.xml"); + private static final File USER_ADMINISTRATOR_FILENAME = new File(COMMON_DIR, "user-administrator.xml"); private static final String USER_ADMINISTRATOR_OID = SystemObjectsType.USER_ADMINISTRATOR.value(); private static final String USER_ADMINISTRATOR_USERNAME = "administrator"; - private static final File ROLE_SUPERUSER_FILENAME = new File( COMMON_DIR, "role-superuser.xml"); + private static final File ROLE_SUPERUSER_FILENAME = new File(COMMON_DIR, "role-superuser.xml"); private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; //222 org. units, 2160 users @@ -55,8 +51,8 @@ public class TestOrgHierarchy extends AbstractModelIntegrationTest { // private static final int[] TREE_LEVELS_USER = {3, 5, 10}; //18 org. units, 86 users - private static final int[] TREE_LEVELS = {2, 8}; - private static final int[] TREE_LEVELS_USER = {3, 5}; + private static final int[] TREE_LEVELS = { 2, 8 }; + private static final int[] TREE_LEVELS_USER = { 3, 5 }; private int count = 0; @@ -79,7 +75,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportOrgStructure() throws Exception { - OperationResult opResult = new OperationResult("===[ addOrgStruct ]==="); + OperationResult opResult = getTestOperationResult(); loadOrgStructure(null, TREE_LEVELS, TREE_LEVELS_USER, "", opResult); opResult.computeStatusIfUnknown(); @@ -87,8 +83,9 @@ public void test100ImportOrgStructure() throws Exception { TestUtil.assertSuccess(opResult); } - private void loadOrgStructure(String parentOid, int[] TREE_SIZE, int[] USER_SIZE, String oidPrefix, - OperationResult result) throws Exception { + private void loadOrgStructure(String parentOid, + int[] TREE_SIZE, int[] USER_SIZE, String oidPrefix, OperationResult result) + throws Exception { if (TREE_SIZE.length == 0) { return; } @@ -96,13 +93,13 @@ private void loadOrgStructure(String parentOid, int[] TREE_SIZE, int[] USER_SIZE for (int i = 0; i < TREE_SIZE[0]; i++) { String newOidPrefix = (TREE_SIZE[0] - i) + "a" + oidPrefix; PrismObject org = createOrg(parentOid, i, newOidPrefix); - LOGGER.info("Creating {}, total {}", org, count); + logger.info("Creating {}, total {}", org, count); String oid = repositoryService.addObject(org, null, result); count++; for (int u = 0; u < USER_SIZE[0]; u++) { PrismObject user = createUser(oid, i, u, newOidPrefix); - LOGGER.info("Creating {}, total {}", user, count); + logger.info("Creating {}, total {}", user, count); repositoryService.addObject(user, null, result); count++; } @@ -149,19 +146,15 @@ private PrismObject createOrg(String parentOid, int i, String oidPrefix } private String createOid(int i, String oidPrefix) { - String oid = StringUtils.rightPad(oidPrefix + Integer.toString(i), 31, 'a'); - - StringBuilder sb = new StringBuilder(); - sb.append(oid.substring(0, 7)); - sb.append('-'); - sb.append(oid.substring(7, 11)); - sb.append('-'); - sb.append(oid.substring(11, 15)); - sb.append('-'); - sb.append(oid.substring(15, 19)); - sb.append('-'); - sb.append(oid.substring(19, 31)); - - return sb.toString(); + String oid = StringUtils.rightPad(oidPrefix + i, 31, 'a'); + return oid.substring(0, 7) + + '-' + + oid.substring(7, 11) + + '-' + + oid.substring(11, 15) + + '-' + + oid.substring(15, 19) + + '-' + + oid.substring(19, 31); } } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestRunAs.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestRunAs.java index edf7c67c3e4..64cee8228d2 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestRunAs.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestRunAs.java @@ -6,23 +6,16 @@ * and European Union Public License. See LICENSE file for details. */ - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; - import java.io.File; import java.util.HashMap; import java.util.Map; -import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.midpoint.util.aspect.ProfilingDataManager; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; +import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; @@ -31,7 +24,7 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.MidPointTestConstants; -import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.util.aspect.ProfilingDataManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -39,9 +32,8 @@ * Mix of various tests for issues that are difficult to replicate using dummy resources. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-longtest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRunAs extends AbstractLongTest { @@ -53,7 +45,7 @@ public class TestRunAs extends AbstractLongTest { private static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); private static final String RESOURCE_DUMMY_OID = "2f454e92-c9e8-11e7-8f60-17bc95e695f8"; - protected static final File USER_ROBOT_FILE = new File (TEST_DIR, "user-robot.xml"); + protected static final File USER_ROBOT_FILE = new File(TEST_DIR, "user-robot.xml"); protected static final String USER_ROBOT_OID = "20b4d7c0-c9e9-11e7-887c-7fe1dc65a3ed"; protected static final String USER_ROBOT_USERNAME = "robot"; @@ -111,8 +103,6 @@ public void test000Sanity() throws Exception { */ @Test public void test100AssignAccountDummyToBarbossa() throws Exception { - final String TEST_NAME = "test100AssignAccountDummyToBarbossa"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -142,8 +132,6 @@ public void test100AssignAccountDummyToBarbossa() throws Exception { */ @Test public void test109UnassignAccountDummyFromBarbossa() throws Exception { - final String TEST_NAME = "test109UnassignAccountDummyFromBarbossa"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -165,8 +153,6 @@ public void test109UnassignAccountDummyFromBarbossa() throws Exception { @Test public void test200CleanupPlain() throws Exception { - final String TEST_NAME = "test200CleanupPlain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -190,13 +176,12 @@ public void test200CleanupPlain() throws Exception { assertSuccess(result); } - /** * Warm up JVM, so we have stable and comparable results */ @Test public void test205WarmUp() throws Exception { - warmUp("test205WarmUp"); + warmUp(); } /** @@ -204,8 +189,6 @@ public void test205WarmUp() throws Exception { */ @Test public void test210BarbossaSetOrganizationPlain() throws Exception { - final String TEST_NAME = "test210BarbossaSetOrganizationPlain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -223,7 +206,7 @@ public void test210BarbossaSetOrganizationPlain() throws Exception { assertSuccess(result); long readCountIncremenet = getCounterIncrement(InternalCounters.REPOSITORY_READ_COUNT); - display("Run time "+(endMillis - starMillis)+"ms, repo read count increment " + readCountIncremenet); + display("Run time " + (endMillis - starMillis) + "ms, repo read count increment " + readCountIncremenet); baselineRunTime = endMillis - starMillis; baselineRepoReadCountIncrement = readCountIncremenet; @@ -236,8 +219,6 @@ public void test210BarbossaSetOrganizationPlain() throws Exception { @Test public void test300CleanupRunAs() throws Exception { - final String TEST_NAME = "test300CleanupRunAs"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -266,17 +247,14 @@ public void test300CleanupRunAs() throws Exception { */ @Test public void test305WarmUp() throws Exception { - warmUp("test305WarmUp"); + warmUp(); } - /** * MID-3844 */ @Test public void test310BarbossaSetOrganizationRunAs() throws Exception { - final String TEST_NAME = "test310BarbossaSetOrganizationRunAs"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -295,18 +273,18 @@ public void test310BarbossaSetOrganizationRunAs() throws Exception { long readCountIncrement = getCounterIncrement(InternalCounters.REPOSITORY_READ_COUNT); long runTimeMillis = (endMillis - starMillis); - display("Run time "+runTimeMillis+"ms, repo read count increment " + readCountIncrement); - long percentRuntimeIncrease = (runTimeMillis - baselineRunTime)*100/baselineRunTime; + display("Run time " + runTimeMillis + "ms, repo read count increment " + readCountIncrement); + long percentRuntimeIncrease = (runTimeMillis - baselineRunTime) * 100 / baselineRunTime; long readCountIncrease = readCountIncrement - baselineRepoReadCountIncrement; display("Increase over baseline", - " run time: "+(runTimeMillis - baselineRunTime) + " (" + percentRuntimeIncrease + "%) \n" + - " repo read: "+ readCountIncrease); + " run time: " + (runTimeMillis - baselineRunTime) + " (" + percentRuntimeIncrease + "%) \n" + + " repo read: " + readCountIncrease); if (readCountIncrease > 2) { fail("High increase over repo read count baseline: " + readCountIncrease + " (expected: at most 2)"); } if (percentRuntimeIncrease > 20) { - fail("Too high run time increase over baseline: "+percentRuntimeIncrease+"% "+baselineRunTime+"ms -> "+runTimeMillis+"ms"); + fail("Too high run time increase over baseline: " + percentRuntimeIncrease + "% " + baselineRunTime + "ms -> " + runTimeMillis + "ms"); } PrismObject userAfter = getUser(USER_BARBOSSA_OID); @@ -316,8 +294,7 @@ public void test310BarbossaSetOrganizationRunAs() throws Exception { } - private void warmUp(final String TEST_NAME) throws Exception { - + private void warmUp() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -338,8 +315,8 @@ private void warmUp(final String TEST_NAME) throws Exception { then(); assertSuccess(result); - long readCountIncremenet = getCounterIncrement(InternalCounters.REPOSITORY_READ_COUNT); - display("Warm up run times: first "+(firstTime)+"ms, last " + lastTime + ", average "+(sumTime/WARM_UP_ROUNDS)+"ms"); + getCounterIncrement(InternalCounters.REPOSITORY_READ_COUNT); + display("Warm up run times: first " + (firstTime) + "ms, last " + lastTime + ", average " + (sumTime / WARM_UP_ROUNDS) + "ms"); PrismObject userAfter = getUser(USER_BARBOSSA_OID); display("User after", userAfter); @@ -361,15 +338,14 @@ private long warmUpRound(int round, Task task, OperationResult result) throws Ex assertSuccess(result); long readCountIncremenet = getCounterIncrement(InternalCounters.REPOSITORY_READ_COUNT); - display("Warm up round "+round+" run time "+(endMillis - starMillis)+"ms, repo read count increment " + readCountIncremenet); + display("Warm up round " + round + " run time " + (endMillis - starMillis) + "ms, repo read count increment " + readCountIncremenet); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_ORGANIZATION, task, result /* no value */); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result /* no value */); - return endMillis - starMillis; + return endMillis - starMillis; } - private void assertUserOrgs(PrismObject user, String organization, String principalUsername) { PrismAsserts.assertPropertyValue(user, UserType.F_ORGANIZATION, createPolyString(organization)); PrismAsserts.assertPropertyValue(user, UserType.F_ORGANIZATIONAL_UNIT, expectedOrgUnits(organization, principalUsername)); @@ -383,5 +359,4 @@ private PolyString[] expectedOrgUnits(String organization, String principalUsern return out; } - } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java index 715c0a40002..9d4d65d29ed 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java @@ -36,10 +36,7 @@ import com.evolveum.midpoint.schema.internals.InternalsConfig; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.DummyAuditService; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.AbstractGuiIntegrationTest; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; @@ -51,8 +48,6 @@ @TestPropertySource(properties = "server.port=18088") public abstract class RestServiceInitializer extends AbstractGuiIntegrationTest { - private static final Trace LOGGER = TraceManager.getTrace(RestServiceInitializer.class); - protected static final File BASE_REPO_DIR = new File("src/test/resources/repo/"); public static final File USER_ADMINISTRATOR_FILE = new File(BASE_REPO_DIR, "user-administrator.xml"); @@ -116,7 +111,7 @@ public abstract class RestServiceInitializer extends AbstractGuiIntegrationTest @Override public void initSystem(Task initTask, OperationResult result) throws Exception { super.initSystem(initTask, result); - LOGGER.trace("initSystem"); + logger.trace("initSystem"); InternalsConfig.encryptionChecks = false; @@ -182,10 +177,6 @@ public PrismContext getPrismContext() { return prismContext; } - public TaskManager getTaskManager() { - return taskManager; - } - public ModelService getModelService() { return modelService; } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java index 7090cbecf66..9eaa647129a 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java @@ -7,11 +7,11 @@ package com.evolveum.midpoint.testing.rest; import com.evolveum.midpoint.common.rest.MidpointAbstractProvider; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.internals.InternalMonitor; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; @@ -84,7 +84,7 @@ public void test001getUserSelfBySomebody() { AssertJUnit.assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - IntegrationTestTools.display("Audit", getDummyAuditService()); + PrismTestUtil.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @@ -107,7 +107,7 @@ public void test002getUserSelfByEgoist() { assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - IntegrationTestTools.display("Audit", getDummyAuditService()); + PrismTestUtil.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @@ -131,7 +131,7 @@ public void test003getUserAdministratorByEgoist() { then(); assertStatus(response, 403); - IntegrationTestTools.display("Audit", getDummyAuditService()); + PrismTestUtil.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @@ -157,7 +157,7 @@ public void test004getUserSelfByHead() { assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - IntegrationTestTools.display("Audit", getDummyAuditService()); + PrismTestUtil.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @@ -181,7 +181,7 @@ public void test005getUserSelfByProxyHead() { then(); assertStatus(response, 403); - IntegrationTestTools.display("Audit", getDummyAuditService()); + PrismTestUtil.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertFailedProxyLogin(SchemaConstants.CHANNEL_REST_URI); } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java index cd6ca13fb28..80935da3013 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java @@ -7,93 +7,84 @@ package com.evolveum.midpoint.testing.rest; -import static org.testng.AssertJUnit.*; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; import java.util.Arrays; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.evolveum.midpoint.gui.test.TestMidPointSpringApplication; - import org.apache.cxf.common.util.Base64Exception; import org.apache.cxf.common.util.Base64Utility; import org.apache.cxf.jaxrs.client.ClientConfiguration; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.transport.local.LocalConduit; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; import org.testng.annotations.Test; import com.evolveum.midpoint.common.rest.MidpointAbstractProvider; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; public class TestSecurityQuestionChallengeResponse extends RestServiceInitializer { - private static final Trace LOGGER = TraceManager.getTrace(TestSecurityQuestionChallengeResponse.class); - @Test - public void testChallengeResponse() throws Exception { + public void testChallengeResponse() { Response response = getUserAdministrator("SecQ"); String challengeBase64 = assertAndGetChallenge(response); String usernameChallenge = null; try { - usernameChallenge = new String(Base64Utility.decode(challengeBase64)); - LOGGER.info("Username challenge: " +usernameChallenge); + usernameChallenge = new String(Base64Utility.decode(challengeBase64)); + logger.info("Username challenge: " + usernameChallenge); } catch (Base64Exception e) { fail("Failed to decode base64 username challenge"); } String secQusernameChallenge = usernameChallenge.replace("username", "administrator"); - LOGGER.info("Username response: " +secQusernameChallenge); + logger.info("Username response: " + secQusernameChallenge); response = getUserAdministrator("SecQ " + Base64Utility.encode(secQusernameChallenge.getBytes())); challengeBase64 = assertAndGetChallenge(response); String answerChallenge; try { answerChallenge = new String(Base64Utility.decode(challengeBase64)); - LOGGER.info("Answer challenge: " +answerChallenge); + logger.info("Answer challenge: " + answerChallenge); } catch (Base64Exception e) { fail("Failed to decode base64 username challenge"); } String secQAnswerChallenge = "{" + "\"user\" : \"administrator\"," + "\"answer\" : [" - + "{ " - + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," - + "\"qans\" : \"5ecr3t\"" - + "}," - + "{ " - + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q002\"," - + "\"qans\" : \"black\"" - + "}" + + "{ " + + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + + "\"qans\" : \"5ecr3t\"" + + "}," + + "{ " + + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q002\"," + + "\"qans\" : \"black\"" + + "}" + "]" + "}"; - LOGGER.info("Answer response: " +secQAnswerChallenge); + logger.info("Answer response: " + secQAnswerChallenge); response = getUserAdministrator("SecQ " + Base64Utility.encode(secQAnswerChallenge.getBytes())); assertEquals("Unexpected status code. Expected 200 but got " + response.getStatus(), 200, response.getStatus()); UserType user = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", user); - LOGGER.info("Returned entity: {}", user.asPrismObject().debugDump()); - + logger.info("Returned entity: {}", user.asPrismObject().debugDump()); } - private String assertAndGetChallenge(Response response){ - assertEquals("Unexpected status code. Expected 401 but was "+ response.getStatus(), 401, response.getStatus()); + private String assertAndGetChallenge(Response response) { + assertEquals("Unexpected status code. Expected 401 but was " + response.getStatus(), 401, response.getStatus()); assertNotNull("Headers null. Something very strange happened", response.getHeaders()); List wwwAuthenticateHeaders = response.getHeaders().get("WWW-Authenticate"); assertNotNull("WWW-Authenticate headers null. Something very strange happened", wwwAuthenticateHeaders); - LOGGER.info("WWW-Authenticate header: " + wwwAuthenticateHeaders); + logger.info("WWW-Authenticate header: " + wwwAuthenticateHeaders); assertEquals("Expected WWW-Authenticate header, but the actual size is " + wwwAuthenticateHeaders.size(), 1, wwwAuthenticateHeaders.size()); String secQHeader = (String) wwwAuthenticateHeaders.iterator().next(); @@ -104,7 +95,7 @@ private String assertAndGetChallenge(Response response){ return challengeBase64; } - private Response getUserAdministrator(String authorizationHeader){ + private Response getUserAdministrator(String authorizationHeader) { WebClient client = WebClient.create(ENDPOINT_ADDRESS, Arrays.asList(getProvider())); ClientConfiguration clientConfig = WebClient.getConfig(client); diff --git a/testing/samples-test/src/test/java/com/evolveum/midpoint/samples/test/AbstractSampleTest.java b/testing/samples-test/src/test/java/com/evolveum/midpoint/samples/test/AbstractSampleTest.java index 66fcdc403df..92526f5ae64 100644 --- a/testing/samples-test/src/test/java/com/evolveum/midpoint/samples/test/AbstractSampleTest.java +++ b/testing/samples-test/src/test/java/com/evolveum/midpoint/samples/test/AbstractSampleTest.java @@ -6,51 +6,43 @@ */ package com.evolveum.midpoint.samples.test; -import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import java.io.File; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; -import java.io.File; - -import static org.testng.AssertJUnit.assertEquals; +import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * Try to import selected samples to a real repository in an initialized system. - * + *

* We cannot import all the samples as some of them are mutually exclusive. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-samples-test-main.xml"}) -@DirtiesContext(classMode=ClassMode.AFTER_CLASS) +@ContextConfiguration(locations = { "classpath:ctx-samples-test-main.xml" }) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractSampleTest extends AbstractModelIntegrationTest { protected static final File SAMPLES_DIRECTORY = new File("target/samples"); - protected static final File SCHEMA_DIRECTORY = new File ("src/test/resources/schema"); + protected static final File SCHEMA_DIRECTORY = new File("src/test/resources/schema"); protected static final File USER_ADMINISTRATOR_FILE = new File("src/test/resources/user-administrator.xml"); - private static final Trace LOGGER = TraceManager.getTrace(AbstractSampleTest.class); - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); // This should discover the connectors - LOGGER.trace("initSystem: trying modelService.postInit()"); + logger.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); - LOGGER.trace("initSystem: modelService.postInit() done"); + logger.trace("initSystem: modelService.postInit() done"); PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); loginSuperUser(userAdministrator); } - } diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java index 4883c30a18a..6bbdc33cff3 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java @@ -6,49 +6,28 @@ */ package com.evolveum.midpoint.testing.sanity; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.prism.util.PrismAsserts.assertEqualsPolyString; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertParentConsistency; -import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull; -import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache; -import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty; -import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb; -import static com.evolveum.midpoint.test.IntegrationTestTools.getAttributeValues; -import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static com.evolveum.midpoint.test.IntegrationTestTools.*; import java.io.File; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; - +import java.util.*; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import javax.xml.ws.Holder; -import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.xnode.MapXNode; -import com.evolveum.midpoint.prism.xnode.XNode; -import com.evolveum.midpoint.util.exception.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.opends.server.core.ModifyOperation; import org.opends.server.protocols.internal.InternalSearchOperation; -import org.opends.server.types.*; import org.opends.server.types.ModificationType; +import org.opends.server.types.*; import org.opends.server.util.ChangeRecordEntry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; @@ -63,14 +42,24 @@ import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; +import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; +import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.crypto.EncryptionException; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.match.MatchingRule; import com.evolveum.midpoint.prism.match.MatchingRuleRegistry; +import com.evolveum.midpoint.prism.path.ItemName; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.prism.xnode.MapXNode; +import com.evolveum.midpoint.prism.xnode.XNode; import com.evolveum.midpoint.schema.CapabilityUtil; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.ResultHandler; @@ -81,12 +70,7 @@ import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.schema.util.ObjectQueryUtil; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.schema.util.ResourceTypeUtil; -import com.evolveum.midpoint.schema.util.SchemaDebugUtil; -import com.evolveum.midpoint.schema.util.SchemaTestConstants; -import com.evolveum.midpoint.schema.util.ShadowUtil; +import com.evolveum.midpoint.schema.util.*; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.Checker; @@ -98,49 +82,21 @@ import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.JAXBUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectShadowChangeDescriptionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectTypeDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SchemaHandlingType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SelectorQualifiedGetOptionsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectAlreadyExistsFaultType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; -import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; -import com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType; -import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; -import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType; -import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import com.evolveum.prism.xml.ns._public.types_3.RawType; +import com.evolveum.prism.xml.ns._public.types_3.*; /** * Sanity test suite. @@ -160,7 +116,7 @@ * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-sanity-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-sanity-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSanity extends AbstractModelIntegrationTest { @@ -177,11 +133,10 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final String RESOURCE_OPENDJ_FILENAME = REPO_DIR_NAME + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; - protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson"); + protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "inetOrgPerson"); private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; - private static final String RESOURCE_DERBY_FILENAME = REPO_DIR_NAME + "resource-derby.xml"; private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab"; @@ -273,7 +228,7 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final File REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE = new File(REQUEST_DIR, "account-modify-bad-path.xml"); private static final String LDIF_WILL_FILENAME = REQUEST_DIR_NAME + "will.ldif"; - private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif"); + private static final File LDIF_WILL_MODIFY_FILE = new File(REQUEST_DIR_NAME, "will-modify.ldif"); private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif"; private static final String WILL_NAME = "wturner"; @@ -282,21 +237,18 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml"; - private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif"; private static final String ELAINE_NAME = "elaine"; - private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif"); - - private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif"; + private static final File LDIF_GIBBS_MODIFY_FILE = new File(REQUEST_DIR_NAME, "gibbs-modify.ldif"); - private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class); + private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif"; private static final String NS_MY = "http://whatever.com/my"; private static final ItemName MY_SHIP_STATE = new ItemName(NS_MY, "shipState"); private static final ItemName MY_DEAD = new ItemName(NS_MY, "dead"); - private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000; + private static final long WAIT_FOR_LOOP_SLEEP_MILLIS = 1000; /** * Unmarshalled resource definition to reach the embedded OpenDJ instance. @@ -319,42 +271,42 @@ public class TestSanity extends AbstractModelIntegrationTest { // This will get called from the superclass to init the repository // It will be called only once public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); - try{ - super.initSystem(initTask, initResult); - - repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); - repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); - - // This should discover the connectors - LOGGER.trace("initSystem: trying modelService.postInit()"); - modelService.postInit(initResult); - LOGGER.trace("initSystem: modelService.postInit() done"); - - login(USER_ADMINISTRATOR_NAME); - - // We need to add config after calling postInit() so it will not be applied. - // we want original logging configuration from the test logback config file, not - // the one from the system config. - repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult); - - // Add broken connector before importing resources - repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult); - - // Need to import instead of add, so the (dynamic) connector reference - // will be resolved - // correctly - importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult); - importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult); - - repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult); - repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult); - repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult); - repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult); - repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult); - repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult); - } catch (Exception ex){ - LOGGER.error("erro: {}", ex); + logger.trace("initSystem"); + try { + super.initSystem(initTask, initResult); + + repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); + repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); + + // This should discover the connectors + logger.trace("initSystem: trying modelService.postInit()"); + modelService.postInit(initResult); + logger.trace("initSystem: modelService.postInit() done"); + + login(USER_ADMINISTRATOR_NAME); + + // We need to add config after calling postInit() so it will not be applied. + // we want original logging configuration from the test logback config file, not + // the one from the system config. + repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult); + + // Add broken connector before importing resources + repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult); + + // Need to import instead of add, so the (dynamic) connector reference + // will be resolved + // correctly + importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult); + importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult); + + repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult); + repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult); + repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult); + repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult); + repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult); + repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult); + } catch (Exception ex) { + logger.error("erro: {}", ex); throw ex; } } @@ -432,7 +384,7 @@ public void test001SelfTests() throws Exception { final String TEST_NAME = "test001SelfTests"; // GIVEN - Task task = taskManager.createTaskInstance(TestSanity.class.getName()+"."+TEST_NAME); + Task task = taskManager.createTaskInstance(TestSanity.class.getName() + "." + TEST_NAME); // WHEN OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task); @@ -448,10 +400,9 @@ public void test001SelfTests() throws Exception { // There may be warning about illegal key size on some platforms. As far as it is warning and not error we are OK // the system will fall back to a interoperable key size if (provisioningSelfTestResult.getStatus() != OperationResultStatus.SUCCESS && provisioningSelfTestResult.getStatus() != OperationResultStatus.WARNING) { - AssertJUnit.fail("Provisioning self-test failed: "+provisioningSelfTestResult); + AssertJUnit.fail("Provisioning self-test failed: " + provisioningSelfTestResult); } -} - + } /** * Test the testResource method. Expect a complete success for now. @@ -461,57 +412,57 @@ public void test001TestConnectionOpenDJ() throws Exception { final String TEST_NAME = "test001TestConnectionOpenDJ"; // GIVEN - try{ - assertNoRepoCache(); + try { + assertNoRepoCache(); - // WHEN - OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID); + // WHEN + OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID); - // THEN + // THEN - assertNoRepoCache(); + assertNoRepoCache(); - displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); + displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); - TestUtil.assertSuccess("testResource has failed", result); + TestUtil.assertSuccess("testResource has failed", result); - OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ"); + OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ"); - PrismObject resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); - resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable(); + PrismObject resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); + resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable(); - assertNoRepoCache(); - assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid()); - display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo); - assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema()); - Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo); - assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement); + assertNoRepoCache(); + assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid()); + display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo); + assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema()); + Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo); + assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement); - PrismObject openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, - null, null, opResult); - display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig); + PrismObject openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, + null, null, opResult); + display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig); - PrismObject openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); - display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel); + PrismObject openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); + display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel); - checkOpenDjResource(resourceTypeOpenDjrepo, "repository"); + checkOpenDjResource(resourceTypeOpenDjrepo, "repository"); - System.out.println("------------------------------------------------------------------"); - display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo))); - System.out.println("------------------------------------------------------------------"); + System.out.println("------------------------------------------------------------------"); + display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo))); + System.out.println("------------------------------------------------------------------"); - checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning"); - checkOpenDjResource(openDjResourceModel.asObjectable(), "model"); - // TODO: model web - } catch (Exception ex){ - LOGGER.info("exception: " + ex); + checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning"); + checkOpenDjResource(openDjResourceModel.asObjectable(), "model"); + // TODO: model web + } catch (Exception ex) { + logger.info("exception: " + ex); throw ex; } } private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException { - OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource"); + OperationResult result = new OperationResult(TestSanity.class.getName() + ".checkRepoOpenDjResource"); PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); checkOpenDjResource(resource.asObjectable(), "repository"); } @@ -567,16 +518,16 @@ private void checkOpenDjSchema(ResourceType resource, String source) throws Sche private void checkOpenDjSchemaHandling(ResourceType resource, String source) { SchemaHandlingType schemaHandling = resource.getSchemaHandling(); - for (ResourceObjectTypeDefinitionType resObjectTypeDef: schemaHandling.getObjectType()) { + for (ResourceObjectTypeDefinitionType resObjectTypeDef : schemaHandling.getObjectType()) { if (resObjectTypeDef.getKind() == ShadowKindType.ACCOUNT) { String name = resObjectTypeDef.getIntent(); - assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig account definition without intent", name); - assertNotNull("Account type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); + assertNotNull("Resource " + resource + " from " + source + " has an schemaHandlig account definition without intent", name); + assertNotNull("Account type " + name + " in " + resource + " from " + source + " does not have object class", resObjectTypeDef.getObjectClass()); } if (resObjectTypeDef.getKind() == ShadowKindType.ENTITLEMENT) { String name = resObjectTypeDef.getIntent(); - assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig entitlement definition without intent", name); - assertNotNull("Entitlement type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); + assertNotNull("Resource " + resource + " from " + source + " has an schemaHandlig entitlement definition without intent", name); + assertNotNull("Entitlement type " + name + " in " + resource + " from " + source + " does not have object class", resObjectTypeDef.getObjectClass()); } } } @@ -588,43 +539,43 @@ private void checkOpenDjConfiguration(PrismObject resource, String private void checkOpenResourceConfiguration(PrismObject resource, String connectorNamespace, String credentialsPropertyName, int numConfigProps, String source) { PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); - assertNotNull("No configuration container in "+resource+" from "+source, configurationContainer); + assertNotNull("No configuration container in " + resource + " from " + source, configurationContainer); PrismContainer configPropsContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); - assertNotNull("No configuration properties container in "+resource+" from "+source, configPropsContainer); - Collection> configProps = configPropsContainer.getValue().getItems(); - assertEquals("Wrong number of config properties in "+resource+" from "+source, numConfigProps, configProps.size()); - PrismProperty credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace,credentialsPropertyName)); + assertNotNull("No configuration properties container in " + resource + " from " + source, configPropsContainer); + Collection> configProps = configPropsContainer.getValue().getItems(); + assertEquals("Wrong number of config properties in " + resource + " from " + source, numConfigProps, configProps.size()); + PrismProperty credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace, credentialsPropertyName)); if (credentialsProp == null) { // The is the heisenbug we are looking for. Just dump the entire damn thing. display("Configuration with the heisenbug", configurationContainer.debugDump()); } - assertNotNull("No "+credentialsPropertyName+" property in "+resource+" from "+source, credentialsProp); - assertEquals("Wrong number of "+credentialsPropertyName+" property value in "+resource+" from "+source, 1, credentialsProp.getValues().size()); + assertNotNull("No " + credentialsPropertyName + " property in " + resource + " from " + source, credentialsProp); + assertEquals("Wrong number of " + credentialsPropertyName + " property value in " + resource + " from " + source, 1, credentialsProp.getValues().size()); PrismPropertyValue credentialsPropertyValue = credentialsProp.getValues().iterator().next(); - assertNotNull("No "+credentialsPropertyName+" property value in "+resource+" from "+source, credentialsPropertyValue); + assertNotNull("No " + credentialsPropertyName + " property value in " + resource + " from " + source, credentialsPropertyValue); if (credentialsPropertyValue.isRaw()) { Object rawElement = credentialsPropertyValue.getRawElement(); - assertTrue("Wrong element class "+rawElement.getClass()+" in "+resource+" from "+source, rawElement instanceof MapXNode); + assertTrue("Wrong element class " + rawElement.getClass() + " in " + resource + " from " + source, rawElement instanceof MapXNode); // Element rawDomElement = (Element)rawElement; MapXNode xmap = (MapXNode) rawElement; - try{ - ProtectedStringType protectedType = new ProtectedStringType(); - prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext()); - // display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement)); + try { + ProtectedStringType protectedType = new ProtectedStringType(); + prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext()); + // display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement)); // assertEquals("Wrong credentials element namespace in "+resource+" from "+source, connectorNamespace, rawDomElement.getNamespaceURI()); // assertEquals("Wrong credentials element local name in "+resource+" from "+source, credentialsPropertyName, rawDomElement.getLocalName()); // Element encryptedDataElement = DOMUtil.getChildElement(rawDomElement, new QName(DOMUtil.NS_XML_ENC, "EncryptedData")); - EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType(); - assertNotNull("No EncryptedData element", encryptedDataType); - } catch (SchemaException ex){ + EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType(); + assertNotNull("No EncryptedData element", encryptedDataType); + } catch (SchemaException ex) { throw new IllegalArgumentException(ex); } // assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI()); // assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName()); } else { Object credentials = credentialsPropertyValue.getValue(); - assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType); - ProtectedStringType credentialsPs = (ProtectedStringType)credentials; + assertTrue("Wrong type of credentials configuration property in " + resource + " from " + source + ": " + credentials.getClass(), credentials instanceof ProtectedStringType); + ProtectedStringType credentialsPs = (ProtectedStringType) credentials; EncryptedDataType encryptedData = credentialsPs.getEncryptedDataType(); assertNotNull("No EncryptedData element", encryptedData); } @@ -705,7 +656,7 @@ private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDelta ObjectDeltaType objectDeltaType = operationType.getObjectDelta(); if (originalDelta.getChangeType() == ChangeTypeType.ADD) { if (objectDeltaType.getChangeType() == originalDelta.getChangeType() && - objectDeltaType.getObjectToAdd() != null) { + objectDeltaType.getObjectToAdd() != null) { ObjectType objectAdded = (ObjectType) objectDeltaType.getObjectToAdd(); if (objectAdded.getClass().equals(originalDelta.getObjectToAdd().getClass())) { return operationType; @@ -722,7 +673,7 @@ private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDelta } private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaException { - OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoDerbyResource"); + OperationResult result = new OperationResult(TestSanity.class.getName() + ".checkRepoDerbyResource"); PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); checkDerbyResource(resource, "repository"); } @@ -735,7 +686,6 @@ private void checkDerbyConfiguration(PrismObject resource, String checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source); } - /** * Test the testResource method. Expect a complete success for now. */ @@ -800,7 +750,7 @@ public void test004Capabilities() // WHEN modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID, - options , objectHolder, resultHolder); + options, objectHolder, resultHolder); ResourceType resource = (ResourceType) objectHolder.value; @@ -844,48 +794,46 @@ public void test004Capabilities() } @Test - public void test005resolveConnectorRef() throws Exception{ + public void test005resolveConnectorRef() throws Exception { PrismObject resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); - OperationResult repoResult = new OperationResult("getObject"); + OperationResult repoResult = new OperationResult("getObject"); - PrismObject uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); - assertNotNull(uObject); + PrismObject uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); + assertNotNull(uObject); - ResourceType resourceType = uObject.asObjectable(); - assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); - assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); + ResourceType resourceType = uObject.asObjectable(); + assertNotNull("Reference on the connector must not be null in resource.", resourceType.getConnectorRef()); + assertNotNull("Missing oid reference on the connector", resourceType.getConnectorRef().getOid()); } @Test - public void test006reimportResourceDummy() throws Exception{ + public void test006reimportResourceDummy() throws Exception { //get object from repo (with version set and try to add it - it should be re-added, without error) - OperationResult repoResult = new OperationResult("getObject"); - - PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); - assertNotNull(resource); - + OperationResult repoResult = new OperationResult("getObject"); - ModelExecuteOptionsType options = new ModelExecuteOptionsType(); - options.setOverwrite(Boolean.TRUE); - options.setIsImport(Boolean.TRUE); - addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); + PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); + assertNotNull(resource); - //TODO: add some asserts + ModelExecuteOptionsType options = new ModelExecuteOptionsType(); + options.setOverwrite(Boolean.TRUE); + options.setIsImport(Boolean.TRUE); + addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); + //TODO: add some asserts - //parse object from file again and try to add it - this should fail, becasue the same object already exists) - resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); + //parse object from file again and try to add it - this should fail, becasue the same object already exists) + resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); try { - Holder resultHolder = new Holder<>(); - options = new ModelExecuteOptionsType(); - options.setIsImport(Boolean.TRUE); + Holder resultHolder = new Holder<>(); + options = new ModelExecuteOptionsType(); + options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), resultHolder); @@ -894,17 +842,16 @@ public void test006reimportResourceDummy() throws Exception{ fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { - LOGGER.info("fault {}", ex.getFaultInfo()); - LOGGER.info("fault {}", ex.getCause()); + logger.info("fault {}", ex.getFaultInfo()); + logger.info("fault {}", ex.getCause()); if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) { - // this is OK, we expect this - } else{ + // this is OK, we expect this + } else { fail("Expected object already exists exception, but got: " + ex.getFaultInfo()); } } - // ResourceType resourceType = uObject.asObjectable(); // assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); // assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); @@ -969,124 +916,124 @@ public void test010AddUser() throws Exception { @Test public void test013AddOpenDjAccountToUser() throws Exception { final String TEST_NAME = "test013AddOpenDjAccountToUser"; - try{ - // GIVEN - checkRepoOpenDjResource(); - assertNoRepoCache(); + try { + // GIVEN + checkRepoOpenDjResource(); + assertNoRepoCache(); - // IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE! - setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE); - // This is not redundant. It checks that the previous command set the policy correctly - assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE); + // IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE! + setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE); + // This is not redundant. It checks that the previous command set the policy correctly + assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE); - ObjectDeltaType objectChange = unmarshallValueFromFile( - REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); + ObjectDeltaType objectChange = unmarshallValueFromFile( + REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); - // WHEN - when(); - OperationResultType result = modifyObjectViaModelWS(objectChange); + // WHEN + when(); + OperationResultType result = modifyObjectViaModelWS(objectChange); - // THEN - then(); - assertNoRepoCache(); - displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); - TestUtil.assertSuccess("modifyObject has failed", result); + // THEN + then(); + assertNoRepoCache(); + displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); + TestUtil.assertSuccess("modifyObject has failed", result); - // Check if user object was modified in the repo + // Check if user object was modified in the repo - OperationResult repoResult = new OperationResult("getObject"); + OperationResult repoResult = new OperationResult("getObject"); - PrismObject repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); - UserType repoUserType = repoUser.asObjectable(); + PrismObject repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); + UserType repoUserType = repoUser.asObjectable(); - repoResult.computeStatus(); - TestUtil.assertSuccess("getObject has failed", repoResult); - display("User (repository)", repoUser); + repoResult.computeStatus(); + TestUtil.assertSuccess("getObject has failed", repoResult); + display("User (repository)", repoUser); - List accountRefs = repoUserType.getLinkRef(); - assertEquals("No accountRefs", 1, accountRefs.size()); - ObjectReferenceType accountRef = accountRefs.get(0); - accountShadowOidOpendj = accountRef.getOid(); - assertFalse(accountShadowOidOpendj.isEmpty()); - - // Check if shadow was created in the repo - - repoResult = new OperationResult("getObject"); - - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, - null, repoResult); - ShadowType repoShadowType = repoShadow.asObjectable(); - repoResult.computeStatus(); - TestUtil.assertSuccess("getObject has failed", repoResult); - display("Shadow (repository)", repoShadow); - assertNotNull(repoShadowType); - assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); + List accountRefs = repoUserType.getLinkRef(); + assertEquals("No accountRefs", 1, accountRefs.size()); + ObjectReferenceType accountRef = accountRefs.get(0); + accountShadowOidOpendj = accountRef.getOid(); + assertFalse(accountShadowOidOpendj.isEmpty()); - assertNotNull("Shadow stored in repository has no name", repoShadowType.getName()); - // Check the "name" property, it should be set to DN, not entryUUID - assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase()); + // Check if shadow was created in the repo - // check attributes in the shadow: should be only identifiers (ICF UID) - String uid = checkRepoShadow(repoShadow); + repoResult = new OperationResult("getObject"); - // check if account was created in LDAP + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, + null, repoResult); + ShadowType repoShadowType = repoShadow.asObjectable(); + repoResult.computeStatus(); + TestUtil.assertSuccess("getObject has failed", repoResult); + display("Shadow (repository)", repoShadow); + assertNotNull(repoShadowType); + assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); - Entry entry = openDJController.searchAndAssertByEntryUuid(uid); + assertNotNull("Shadow stored in repository has no name", repoShadowType.getName()); + // Check the "name" property, it should be set to DN, not entryUUID + assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase()); - display("LDAP account", entry); + // check attributes in the shadow: should be only identifiers (ICF UID) + String uid = checkRepoShadow(repoShadow); - OpenDJController.assertAttribute(entry, "uid", "jack"); - OpenDJController.assertAttribute(entry, "givenName", "Jack"); - OpenDJController.assertAttribute(entry, "sn", "Sparrow"); - OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow"); - OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow"); - // The "l" attribute is assigned indirectly through schemaHandling and - // config object - OpenDJController.assertAttribute(entry, "l", "Black Pearl"); + // check if account was created in LDAP - assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry)); + Entry entry = openDJController.searchAndAssertByEntryUuid(uid); - originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword"); - assertNotNull("Pasword was not set on create", originalJacksLdapPassword); - System.out.println("password after create: " + originalJacksLdapPassword); + display("LDAP account", entry); - // Use getObject to test fetch of complete shadow + OpenDJController.assertAttribute(entry, "uid", "jack"); + OpenDJController.assertAttribute(entry, "givenName", "Jack"); + OpenDJController.assertAttribute(entry, "sn", "Sparrow"); + OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow"); + OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow"); + // The "l" attribute is assigned indirectly through schemaHandling and + // config object + OpenDJController.assertAttribute(entry, "l", "Black Pearl"); - assertNoRepoCache(); + assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry)); - Holder resultHolder = new Holder<>(); - Holder objectHolder = new Holder<>(); - SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); + originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword"); + assertNotNull("Pasword was not set on create", originalJacksLdapPassword); + System.out.println("password after create: " + originalJacksLdapPassword); - // WHEN - modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, - options, objectHolder, resultHolder); + // Use getObject to test fetch of complete shadow - // THEN - assertNoRepoCache(); - displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); - TestUtil.assertSuccess("getObject has failed", resultHolder.value); + assertNoRepoCache(); - ShadowType modelShadow = (ShadowType) objectHolder.value; - display("Shadow (model)", modelShadow); + Holder resultHolder = new Holder<>(); + Holder objectHolder = new Holder<>(); + SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); - AssertJUnit.assertNotNull(modelShadow); - AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); + // WHEN + modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, + options, objectHolder, resultHolder); - assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow"); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow"); - assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl"); - assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense")); - assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress")); - - assertNotNull("Activation is null (model)", modelShadow.getActivation()); - assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); - } catch (Exception ex){ - LOGGER.info("ERROR: {}", ex); + // THEN + assertNoRepoCache(); + displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); + TestUtil.assertSuccess("getObject has failed", resultHolder.value); + + ShadowType modelShadow = (ShadowType) objectHolder.value; + display("Shadow (model)", modelShadow); + + AssertJUnit.assertNotNull(modelShadow); + AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); + + assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow"); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow"); + assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl"); + assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense")); + assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress")); + + assertNotNull("Activation is null (model)", modelShadow.getActivation()); + assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); + } catch (Exception ex) { + logger.info("ERROR: {}", ex); throw ex; } @@ -1189,7 +1136,7 @@ public void test014AddDerbyAccountToUser() throws IOException, JAXBException, Fa Holder resultHolder = new Holder<>(); Holder objectHolder = new Holder<>(); - SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType (); + SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby, @@ -1271,7 +1218,7 @@ public boolean handle(PrismObject prismObject, OperationResult paren try { PrismAsserts.assertEquals("Wrong shadow name", caseIgnoreMatchingRule, shadow.getName().getOrig(), icfName); } catch (SchemaException e) { - throw new IllegalArgumentException(e.getMessage(),e); + throw new IllegalArgumentException(e.getMessage(), e); } assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "uid"))); assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "cn"))); @@ -1329,7 +1276,7 @@ public void test020ModifyUser() throws Exception { List accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { - assertTrue("No OID in "+accountRef+" in "+repoUserType, + assertTrue("No OID in " + accountRef + " in " + repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); @@ -1366,7 +1313,7 @@ private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryE private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException { display(entry); - OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com"); + OpenDJController.assertDn(entry, "uid=" + uid + ",ou=people,dc=example,dc=com"); OpenDJController.assertAttribute(entry, "uid", uid); if (givenName == null) { OpenDJController.assertAttribute(entry, "givenName"); @@ -1540,7 +1487,6 @@ public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal); } - @Test public void test029ModifyAccountDjBadPath() throws Exception { final String TEST_NAME = "test029ModifyAccountDjBadPath"; @@ -1631,7 +1577,7 @@ public void test030DisableUser() throws Exception { List accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { - assertTrue("No OID in "+accountRef+" in "+repoUserType, + assertTrue("No OID in " + accountRef + " in " + repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } @@ -1733,7 +1679,7 @@ public void test031EnableUser() throws Exception { List accountRefs = repoUser.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { - assertTrue("No OID in "+accountRef+" in "+repoUser, + assertTrue("No OID in " + accountRef + " in " + repoUser, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } @@ -1844,7 +1790,7 @@ public void test040UnlinkDerbyAccountFromUser() // only OpenDJ account should be left now assertEquals(1, accountRefs.size()); ObjectReferenceType ref = accountRefs.get(0); - assertEquals("Wrong OID in accountRef in "+repoUser, accountShadowOidOpendj, ref.getOid()); + assertEquals("Wrong OID in accountRef in " + repoUser, accountShadowOidOpendj, ref.getOid()); } @@ -1935,7 +1881,7 @@ public void test047RenameUser() throws Exception { List accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.iterator().next(); - assertEquals("Wrong OID in "+accountRef+" in "+repoUserType, + assertEquals("Wrong OID in " + accountRef + " in " + repoUserType, accountShadowOidOpendj, accountRef.getOid()); // Check if shadow is still in the repo and that it is untouched @@ -1957,7 +1903,6 @@ public void test047RenameUser() throws Exception { assertOpenDJAccountJack(uid, "jsparrow"); } - /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). @@ -2188,7 +2133,6 @@ public void test101AccountOwnerAfterRole() throws Exception { System.out.println("Account " + accountShadowOidGuybrushOpendj + " has owner " + ObjectTypeUtil.toShortString(user)); } - @Test public void test102AssignRoleCaptain() throws Exception { final String TEST_NAME = "test102AssignRoleCaptain"; @@ -2266,7 +2210,6 @@ public void test102AssignRoleCaptain() throws Exception { } - /** * Assign the same "captain" role again, this time with a slightly different assignment parameters. */ @@ -2347,7 +2290,6 @@ public void test103AssignRoleCaptainAgain() throws Exception { } - @Test public void test105ModifyAccount() throws Exception { final String TEST_NAME = "test105ModifyAccount"; @@ -2363,7 +2305,7 @@ public void test105ModifyAccount() throws Exception { Task task = taskManager.createTaskInstance(); OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); - PrismObject shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); + PrismObject shadow = modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); ShadowType shadowType = shadow.asObjectable(); @@ -2375,20 +2317,19 @@ public void test105ModifyAccount() throws Exception { // PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition()); // PrismPropertyValue valToDelte = new PrismPropertyValue("A"); // valToDelte.setParent(deleteDelta); - Collection> values= item.getValues(); - for (PrismPropertyValue val : values){ - if ("A".equals(val.getValue())){ + Collection> values = item.getValues(); + for (PrismPropertyValue val : values) { + if ("A".equals(val.getValue())) { deleteDelta.addValueToDelete(val.clone()); } } - ObjectDelta delta = prismContext.deltaFactory().object().create(ShadowType.class, ChangeType.MODIFY); delta.addModification(deleteDelta); delta.setOid(accountShadowOidGuybrushOpendj); Collection> deltas = new ArrayList<>(); deltas.add(delta); - LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------"); + logger.info("-------->>EXECUTE DELETE MODIFICATION<<------------"); modelService.executeChanges(deltas, null, task, parentResult); // THEN @@ -2475,7 +2416,6 @@ public void test104AssignRoleJudge() throws Exception { } - @Test public void test107UnassignRolePirate() throws Exception { final String TEST_NAME = "test107UnassignRolePirate"; @@ -2505,7 +2445,6 @@ public void test107UnassignRolePirate() throws Exception { repoResult.computeStatus(); display("User (repository)", repoUser); - List accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); @@ -2555,7 +2494,6 @@ public void test107UnassignRolePirate() throws Exception { // TODO: Derby - } @Test @@ -2589,7 +2527,6 @@ public void test108UnassignRoleCaptain() throws Exception { repoResult.computeStatus(); display("User (repository)", repoUser); - List accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); @@ -2639,7 +2576,6 @@ public void test108UnassignRoleCaptain() throws Exception { // TODO: Derby - } /** @@ -2704,7 +2640,6 @@ public void test109UnassignRoleCaptainAgain() throws Exception { } - // Synchronization tests /** @@ -2730,7 +2665,6 @@ public void test300LiveSyncInit() throws Exception { repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result); - // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task @@ -2801,19 +2735,19 @@ public void timeout() { OperationResult taskResult = task.getResult(); AssertJUnit.assertNotNull(taskResult); - assertTrue("Task result is not a success, it is "+taskResult, taskResult.isSuccess()); + assertTrue("Task result is not a success, it is " + taskResult, taskResult.isSuccess()); - final Object tokenAfter = findSyncToken(task); - display("Sync token after", tokenAfter.toString()); - lastSyncToken = (Integer)tokenAfter; + final Object tokenAfter = findSyncToken(task); + display("Sync token after", tokenAfter.toString()); + lastSyncToken = (Integer) tokenAfter; - checkAllShadows(); + checkAllShadows(); - // Try without options. The results should NOT be there - // MID-4670 - task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result); - taskResult = task.getResult(); - AssertJUnit.assertNull("Unexpected task result", taskResult); + // Try without options. The results should NOT be there + // MID-4670 + task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result); + taskResult = task.getResult(); + AssertJUnit.assertNull("Unexpected task result", taskResult); } @@ -2849,7 +2783,7 @@ public void test301LiveSyncCreate() throws Exception { // Search for the user that should be created now UserType user = searchUserByName(WILL_NAME); - PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); + PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); assertNotNull(user.getLinkRef()); assertFalse(user.getLinkRef().isEmpty()); // AssertJUnit.assertEquals(user.getName(), WILL_NAME); @@ -2882,10 +2816,10 @@ public void test302LiveSyncModify() throws Exception { // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result); // Search for the user that should be created now - UserType user = searchUserByName (WILL_NAME); + UserType user = searchUserByName(WILL_NAME); // AssertJUnit.assertEquals(WILL_NAME, user.getName()); - PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); + PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); @@ -2946,7 +2880,7 @@ public void test303LiveSyncLink() throws Exception { String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); - assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName()); + assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); @@ -2989,7 +2923,7 @@ public void test304LiveSyncCreateNoLocation() throws Exception { String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); - assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); + assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); // assertEquals("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); Collection localities = getAttributeValues(account, new QName(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS.getNamespaceURI(), "l")); assertNotNull("null value list for attribute 'l'", localities); @@ -3003,14 +2937,14 @@ public void test304LiveSyncCreateNoLocation() throws Exception { private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) { final Object tokenAfter = findSyncToken(syncCycle); display("Sync token after", tokenAfter.toString()); - int tokenAfterInt = (Integer)tokenAfter; + int tokenAfterInt = (Integer) tokenAfter; int expectedToken = lastSyncToken + increment; lastSyncToken = tokenAfterInt; assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt); } private int findSyncToken(Task syncCycle) { - return (Integer)findSyncTokenObject(syncCycle); + return (Integer) findSyncTokenObject(syncCycle); } private Object findSyncTokenObject(Task syncCycle) { @@ -3019,7 +2953,7 @@ private Object findSyncTokenObject(Task syncCycle) { if (tokenProperty != null) { Collection values = tokenProperty.getRealValues(); if (values.size() > 1) { - throw new IllegalStateException("Too must values in token "+tokenProperty); + throw new IllegalStateException("Too must values in token " + tokenProperty); } token = values.iterator().next(); } @@ -3141,8 +3075,8 @@ public void timeout() { AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); - assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp()); - assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp()); + assertNotNull("Null lastRunStartTimestamp in " + task, task.getLastRunStartTimestamp()); + assertNotNull("Null lastRunFinishTimestamp in " + task, task.getLastRunFinishTimestamp()); long importDuration = task.getLastRunFinishTimestamp() - task.getLastRunStartTimestamp(); double usersPerSec = (task.getProgress() * 1000) / importDuration; @@ -3191,7 +3125,7 @@ public void timeout() { // TODO: use another account, not guybrush - display("Users after import "+uobjects.getObject().size()); + display("Users after import " + uobjects.getObject().size()); for (ObjectType oo : uobjects.getObject()) { UserType user = (UserType) oo; @@ -3215,7 +3149,7 @@ public void timeout() { continue; } - assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null || + assertTrue("User " + user.getName() + " is disabled (" + user.getActivation().getAdministrativeStatus() + ")", user.getActivation() == null || user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED); List accountRefs = user.getLinkRef(); @@ -3252,8 +3186,8 @@ public void timeout() { } - private String getUserLocality(UserType user){ - return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere"; + private String getUserLocality(UserType user) { + return user.getLocality() != null ? user.getLocality().getOrig() : "middle of nowhere"; } @Test @@ -3272,10 +3206,8 @@ public void test420RecomputeUsers() throws Exception { getUserDefinition()); repositoryService.modifyObject(UserType.class, changeAddRoleCaptain.getOid(), modifications, result); - // TODO: setup more "inconsistent" state - // Add reconciliation task. This will trigger reconciliation importObjectFromFile(TASK_USER_RECOMPUTE_FILENAME, result); @@ -3351,7 +3283,7 @@ public void timeout() { displayJaxb("User (repository)", repoUser, new QName("user")); List accountRefs = repoUser.getLinkRef(); - assertEquals("Wrong number of accountRefs after recompute for user "+repoUser.getName(), 1, accountRefs.size()); + assertEquals("Wrong number of accountRefs after recompute for user " + repoUser.getName(), 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); @@ -3360,8 +3292,8 @@ public void timeout() { repoResult = new OperationResult("getObject"); - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, - null, repoResult); + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, + null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); @@ -3434,7 +3366,6 @@ public void test440ReconcileResourceOpenDj() throws Exception { repoAddObjectFromFile(TASK_OPENDJ_RECON_FILENAME, result); - // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task @@ -3553,7 +3484,6 @@ public void timeout() { String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); - // QueryType query = QueryUtil.createNameQuery(ELAINE_NAME); // ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(UserType.class, prismContext, UserType.F_NAME, ELAINE_NAME)); ObjectQuery query = ObjectQueryUtil.createNameQuery(ELAINE_NAME, prismContext); @@ -3637,7 +3567,7 @@ public void test480ListResources() throws Exception { assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size()); // TODO - for(ObjectType object: objectListHolder.value.getObject()) { + for (ObjectType object : objectListHolder.value.getObject()) { // Marshalling may fail even though the Java object is OK so test for it String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML); } @@ -3677,7 +3607,7 @@ public void test485ListResourcesWithBrokenResource() throws Exception { } @Test - public void test500NotifyChangeCreateAccount() throws Exception{ + public void test500NotifyChangeCreateAccount() throws Exception { Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME); display("Entry from LDIF", ldifEntry); @@ -3685,13 +3615,13 @@ public void test500NotifyChangeCreateAccount() throws Exception{ List attrs = ldifEntry.getAttribute("entryUUID"); AttributeValue val = null; - if (attrs == null){ - for (Attribute a : attributes){ - if (a.getName().equals("entryUUID")){ + if (attrs == null) { + for (Attribute a : attributes) { + if (a.getName().equals("entryUUID")) { val = a.iterator().next(); } } - } else{ + } else { val = attrs.get(0).iterator().next(); } @@ -3741,10 +3671,10 @@ public void test500NotifyChangeCreateAccount() throws Exception{ } @Test - public void test501NotifyChangeModifyAccount() throws Exception{ + public void test501NotifyChangeModifyAccount() throws Exception { final String TEST_NAME = "test501NotifyChangeModifyAccount"; - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3770,9 +3700,9 @@ public void test501NotifyChangeModifyAccount() throws Exception{ delta.getItemDelta().add(mod1); delta.setOid(oid); - LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1)); + logger.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1)); - LOGGER.info("delta: {}", DebugUtil.dump(mod1)); + logger.info("delta: {}", DebugUtil.dump(mod1)); changeDescription.setObjectDelta(delta); @@ -3797,7 +3727,7 @@ public void test501NotifyChangeModifyAccount() throws Exception{ } @Test - public void test502NotifyChangeModifyAccountPassword() throws Exception{ + public void test502NotifyChangeModifyAccountPassword() throws Exception { final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); @@ -3811,7 +3741,7 @@ public void test502NotifyChangeModifyAccountPassword() throws Exception{ String newPassword = "newPassword"; - openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword); + openDJController.modifyReplace("uid=" + ANGELIKA_NAME + "," + openDJController.getSuffixPeople(), "userPassword", newPassword); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); @@ -3827,9 +3757,9 @@ public void test502NotifyChangeModifyAccountPassword() throws Exception{ delta.getItemDelta().add(passwordDelta); delta.setOid(oid); - LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta)); + logger.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta)); - LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta)); + logger.info("delta: {}", DebugUtil.dump(passwordDelta)); changeDescription.setObjectDelta(delta); @@ -3853,7 +3783,7 @@ public void test502NotifyChangeModifyAccountPassword() throws Exception{ } @Test - public void test503NotifyChangeDeleteAccount() throws Exception{ + public void test503NotifyChangeDeleteAccount() throws Exception { final String TEST_NAME = "test503NotifyChangeDeleteAccount"; PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); @@ -3893,8 +3823,6 @@ public void test503NotifyChangeDeleteAccount() throws Exception{ } - - @Test public void test999Shutdown() throws Exception { taskManager.shutdown(); @@ -3936,7 +3864,7 @@ private String checkRepoShadow(PrismObject repoShadow) { } } - assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers); + assertFalse("Shadow " + repoShadow + " has unexpected elements", hasOthers); assertNotNull(uid); return uid; @@ -4000,7 +3928,7 @@ private UserType searchUserByName(String name) throws Exception { private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, int increment, final OperationResult result) throws Exception { - basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result); + basicWaitForSyncChangeDetection(syncCycle, (int) ((Integer) tokenBefore), increment, result); } private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment, @@ -4017,7 +3945,7 @@ public boolean check() throws CommonException { syncCycle.refresh(result); display("SyncCycle while waiting for sync cycle to detect change", syncCycle); if (syncCycle.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) { - throw new IllegalStateException("Task not runnable: "+syncCycle.getExecutionStatus()+"; "+syncCycle); + throw new IllegalStateException("Task not runnable: " + syncCycle.getExecutionStatus() + "; " + syncCycle); } int tokenNow = findSyncToken(syncCycle); display("tokenNow = " + tokenNow); @@ -4029,7 +3957,7 @@ public boolean check() throws CommonException { public void timeout() { // No reaction, the test will fail right after return from this } - }, timeout, WAIT_FOR_LOOP_SLEEP_MILIS); + }, timeout, WAIT_FOR_LOOP_SLEEP_MILLIS); } private void setAssignmentEnforcement(AssignmentPolicyEnforcementType enforcementType) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { @@ -4051,7 +3979,7 @@ private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnfor } private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { - LOGGER.trace("Checking all shadows"); + logger.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker checker = null; IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext); @@ -4062,18 +3990,18 @@ public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedO String value = getAttributeValue(repoShadow, name); RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next(); - if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)){ + if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)) { return value.toLowerCase(); } return value; } - protected void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { + protected void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } - protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { + protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java index fb2e5e990c5..1f95834e186 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java @@ -6,40 +6,23 @@ */ package com.evolveum.midpoint.testing.story; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; -import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache; import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb; -import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.IOException; -import java.util.*; - +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.*; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.test.asserter.LinksAsserter; -import com.evolveum.midpoint.test.asserter.ShadowAsserter; -import com.evolveum.midpoint.test.asserter.ShadowReferenceAsserter; -import com.evolveum.midpoint.test.asserter.UserAsserter; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import org.apache.commons.lang.StringUtils; import org.opends.server.types.Entry; import org.opends.server.util.EmbeddedUtils; @@ -51,44 +34,44 @@ import org.testng.annotations.Test; import org.w3c.dom.Element; +import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; +import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.crypto.EncryptionException; +import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.path.ItemName; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.schema.DeltaConvertor; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SearchResultList; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; -import com.evolveum.midpoint.schema.processor.ResourceAttribute; -import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; -import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.schema.processor.ResourceSchema; +import com.evolveum.midpoint.schema.processor.*; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.schema.util.MiscSchemaUtil; -import com.evolveum.midpoint.schema.util.ObjectQueryUtil; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.schema.util.ResourceTypeUtil; -import com.evolveum.midpoint.schema.util.SchemaTestConstants; -import com.evolveum.midpoint.schema.util.ShadowUtil; +import com.evolveum.midpoint.schema.util.*; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.asserter.LinksAsserter; +import com.evolveum.midpoint.test.asserter.ShadowAsserter; +import com.evolveum.midpoint.test.asserter.ShadowReferenceAsserter; +import com.evolveum.midpoint.test.asserter.UserAsserter; import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointAsserts; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; +import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.RawType; @@ -119,8 +102,8 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final String RESOURCE_OPENDJ_FILENAME = TEST_DIR + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; - private static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson"); - private static final QName RESOURCE_OPENDJ_GROUP_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"groupOfUniqueNames"); + private static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "inetOrgPerson"); + private static final QName RESOURCE_OPENDJ_GROUP_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "groupOfUniqueNames"); private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; private static final QName RESOURCE_OPENDJ_SECONDARY_IDENTIFIER = new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); @@ -236,8 +219,6 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final File LDIF_MODIFY_RENAME_FILE = new File(TEST_DIR, "modify-rename.ldif"); - private static final Trace LOGGER = TraceManager.getTrace(TestConsistencyMechanism.class); - private static final String NS_MY = "http://whatever.com/my"; private static final QName MY_SHIP_STATE = new QName(NS_MY, "shipState"); @@ -257,7 +238,7 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { // This will get called from the superclass to init the repository // It will be called only once public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); @@ -265,9 +246,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); // This should discover the connectors - LOGGER.trace("initSystem: trying modelService.postInit()"); + logger.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); - LOGGER.trace("initSystem: modelService.postInit() done"); + logger.trace("initSystem: modelService.postInit() done"); login(USER_ADMINISTRATOR_NAME); @@ -302,7 +283,7 @@ public void startResources() throws Exception { * superclass so individual tests may avoid starting OpenDJ. */ @AfterClass - public static void stopResources() throws Exception { + public void stopResources() { openDJController.stop(); } @@ -311,7 +292,6 @@ public static void stopResources() throws Exception { */ @Test public void test000Integrity() throws Exception { - final String TEST_NAME = "test000Integrity"; assertNotNull(modelWeb); assertNotNull(modelService); assertNotNull(repositoryService); @@ -329,7 +309,7 @@ public void test000Integrity() throws Exception { assertNoRepoCache(); - OperationResult result = new OperationResult(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Check if OpenDJ resource was imported correctly @@ -424,20 +404,17 @@ public void test100AddUser() throws Exception { then(); assertSuccess(repoResult); - assertUser(uObject,"repo") - .assertOid(USER_JACK_OID) - .assertFullName(userType.getFullName().getOrig()); + assertUser(uObject, "repo") + .assertOid(USER_JACK_OID) + .assertFullName(userType.getFullName().getOrig()); } - /** * Add account to user. This should result in account provisioning. Check if * that happens in repo and in LDAP. */ @Test public void test110PrepareOpenDjWithJackieAccounts() throws Exception { - final String TEST_NAME = "test110PrepareOpenDjWithJackieAccounts"; - Task task = getTestTask(); OperationResult parentResult = task.getResult(); @@ -476,13 +453,13 @@ public void test110PrepareOpenDjWithJackieAccounts() throws Exception { .assertKind(ShadowKindType.ACCOUNT) .assertIntent("internal") .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() - .assertValue(LDAP_ATTRIBUTE_UID, ACCOUNT_JACKIE_LDAP_UID) - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") - .assertValue(LDAP_ATTRIBUTE_CN, "Jack Sparrow") - .assertValue(LDAP_ATTRIBUTE_SN, "Sparrow") - .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() + .assertValue(LDAP_ATTRIBUTE_UID, ACCOUNT_JACKIE_LDAP_UID) + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") + .assertValue(LDAP_ATTRIBUTE_CN, "Jack Sparrow") + .assertValue(LDAP_ATTRIBUTE_SN, "Sparrow") + .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) .end() .assertResource(RESOURCE_OPENDJ_OID) .assertAdministrativeStatus(ActivationStatusType.ENABLED); @@ -491,8 +468,6 @@ public void test110PrepareOpenDjWithJackieAccounts() throws Exception { @Test public void test111prepareOpenDjWithDenielsAccounts() throws Exception { - final String TEST_NAME = "test111prepareOpenDjWithDenielsAccounts"; - Task task = getTestTask(); OperationResult parentResult = task.getResult(); @@ -520,11 +495,11 @@ public void test111prepareOpenDjWithDenielsAccounts() throws Exception { .attributes() .assertHasPrimaryIdentifier() .assertHasSecondaryIdentifier() - .assertValue(LDAP_ATTRIBUTE_UID, ACCOUNT_DENIELS_LDAP_UID) - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") - .assertValue(LDAP_ATTRIBUTE_CN, "Jack Deniels") - .assertValue(LDAP_ATTRIBUTE_SN, "Deniels") - .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) + .assertValue(LDAP_ATTRIBUTE_UID, ACCOUNT_DENIELS_LDAP_UID) + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") + .assertValue(LDAP_ATTRIBUTE_CN, "Jack Deniels") + .assertValue(LDAP_ATTRIBUTE_SN, "Deniels") + .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) .end() .assertResource(RESOURCE_OPENDJ_OID) .assertAdministrativeStatus(ActivationStatusType.ENABLED); @@ -536,7 +511,6 @@ public void test111prepareOpenDjWithDenielsAccounts() throws Exception { @Test public void test120AddAccountAlreadyExistLinked() throws Exception { - final String TEST_NAME = "test120AddAccountAlreadyExistLinked"; Task task = taskManager.createTaskInstance(); OperationResult parentResult = new OperationResult("Add account already exist linked"); @@ -548,12 +522,11 @@ public void test120AddAccountAlreadyExistLinked() throws Exception { PrismObject userJackieBefore = getUser(USER_JACKIE_OID); UserAsserter.forUser(userJackieBefore).assertLinks(0); - PrismObject userJackBefore = getUser(USER_JACK_OID); UserAsserter.forUser(userJackBefore) .assertLinks(1) .links() - .link(ACCOUNT_JACKIE_OID); + .link(ACCOUNT_JACKIE_OID); // //check if the jackie account already exists on the resource PrismObject existingJackieAccount = getShadowRepo(ACCOUNT_JACKIE_OID); @@ -576,13 +549,13 @@ public void test120AddAccountAlreadyExistLinked() throws Exception { .assertKind(ShadowKindType.ACCOUNT) .assertIntent("internal") .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() - .assertValue(LDAP_ATTRIBUTE_UID, "jackie1") - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") - .assertValue(LDAP_ATTRIBUTE_CN, "Jack Russel") - .assertValue(LDAP_ATTRIBUTE_SN, "Russel") - .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() + .assertValue(LDAP_ATTRIBUTE_UID, "jackie1") + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jack") + .assertValue(LDAP_ATTRIBUTE_CN, "Jack Russel") + .assertValue(LDAP_ATTRIBUTE_SN, "Russel") + .assertNoAttribute(LDAP_ATTRIBUTE_CAR_LICENCE) .end() .assertResource(RESOURCE_OPENDJ_OID) .assertAdministrativeStatus(ActivationStatusType.ENABLED); @@ -590,11 +563,8 @@ public void test120AddAccountAlreadyExistLinked() throws Exception { // checkAccount(accountOid, "jackie1", "Jack", "Russel", "Jack Russel", task, parentResult); } - @Test public void test122AddAccountAlreadyExistUnlinked() throws Exception { - final String TEST_NAME = "test122AddAccountAlreadyExistUnlinked"; - // GIVEN OperationResult parentResult = new OperationResult("Add account already exist unlinked."); Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_FILE); @@ -641,11 +611,9 @@ public void test122AddAccountAlreadyExistUnlinked() throws Exception { //MID-1595, MID-1577 @Test(enabled = false) public void test124AddAccountDirectAlreadyExists() throws Exception { - final String TEST_NAME = "test124AddAccountDirectAlreadyExists"; Task task = getTestTask(); OperationResult parentResult = task.getResult(); - try { repoAddObjectFromFile(USER_ABOMBA_FILENAME, parentResult); @@ -659,7 +627,7 @@ public void test124AddAccountDirectAlreadyExists() throws Exception { String abombaOid = getLinkRefOid(USER_ABOMBA_OID, RESOURCE_OPENDJ_OID); ShadowType abombaShadow = repositoryService.getObject(ShadowType.class, abombaOid, null, parentResult).asObjectable(); - assertShadowName(abombaShadow,"uid=abomba,OU=people,DC=example,DC=com"); + assertShadowName(abombaShadow, "uid=abomba,OU=people,DC=example,DC=com"); repoAddObjectFromFile(USER_ABOM_FILENAME, parentResult); ObjectDelta abomDelta = createModifyUserAddAccount(USER_ABOM_OID, resourceTypeOpenDjrepo.asPrismObject(), "contractor"); @@ -705,34 +673,30 @@ public void test124AddAccountDirectAlreadyExists() throws Exception { // this is expected } - LOGGER.info("starting second execution request for user abomba"); + logger.info("starting second execution request for user abomba"); OperationResult result = new OperationResult("Add account already exist result."); ObjectDelta abombaDelta2 = createModifyUserAddAccount(USER_ABOMBA_OID, resourceTypeOpenDjrepo.asPrismObject(), "contractor"); executeChanges(abombaDelta2, null, task, parentResult); - String abombaOid2 = assertUserOneAccountRef(USER_ABOMBA_OID); ShadowType abombaShadow2 = repositoryService.getObject(ShadowType.class, abombaOid2, null, result).asObjectable(); assertShadowName(abombaShadow2, "uid=abomba,OU=people,DC=example,DC=com"); - result.computeStatus(); - LOGGER.info("Displaying execute changes result"); + logger.info("Displaying execute changes result"); display(result); - } catch (Exception ex) { - LOGGER.info("error: " + ex.getMessage(), ex); + logger.info("error: " + ex.getMessage(), ex); throw ex; } } @Test public void test130DeleteObjectNotFound() throws Exception { - final String TEST_NAME = "test130DeleteObjectNotFound"; - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddShadowFromFile(ACCOUNT_GUYBRUSH_FILE, parentResult); repoAddObjectFromFile(USER_GUYBRUSH_FILENAME, parentResult); @@ -777,13 +741,12 @@ public void test130DeleteObjectNotFound() throws Exception { /** * Modify account not found => reaction: Delete account - * + *

* no assignemnt - only linkRef to non existent account */ @SuppressWarnings("unchecked") @Test public void test140ModifyObjectNotFoundLinkedAccount() throws Exception { - final String TEST_NAME = "test140ModifyObjectNotFoundLinkedAccount"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -794,12 +757,12 @@ public void test140ModifyObjectNotFoundLinkedAccount() throws Exception { UserAsserter.forUser(userBefore) .assertLinks(1) .links() - .link(ACCOUNT_GUYBRUSH_OID); + .link(ACCOUNT_GUYBRUSH_OID); // WHEN ObjectDelta delta = prismContext.deltaFor(ShadowType.class) .property(ItemPath.create(ShadowType.F_ATTRIBUTES, new ItemName(MidPointConstants.NS_RI, "roomNumber"))) - .replace("cabin") + .replace("cabin") .asObjectDelta(ACCOUNT_GUYBRUSH_OID); try { @@ -840,19 +803,15 @@ public void test140ModifyObjectNotFoundLinkedAccount() throws Exception { // repositoryService.deleteObject(UserType.class, USER_GUYBRUSH_OID, result); } - - /** * Modify account not found => reaction: Re-create account, apply changes. - * + *

* assignemt with non-existent account */ @Test public void test142ModifyObjectNotFoundAssignedAccount() throws Exception { - final String TEST_NAME = "test142ModifyObjectNotFoundAssignedAccountq"; - // GIVEN - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddShadowFromFile(ACCOUNT_GUYBRUSH_MODIFY_DELETE_FILE, parentResult); repoAddObjectFromFile(USER_GUYBRUSH_NOT_FOUND_FILENAME, parentResult); @@ -861,7 +820,7 @@ public void test142ModifyObjectNotFoundAssignedAccount() throws Exception { UserAsserter.forUser(userBefore) .assertLinks(1) .links() - .link(ACCOUNT_GUYBRUSH_MODIFY_DELETE_OID); + .link(ACCOUNT_GUYBRUSH_MODIFY_DELETE_OID); Task task = taskManager.createTaskInstance(); @@ -869,9 +828,9 @@ public void test142ModifyObjectNotFoundAssignedAccount() throws Exception { when(); ObjectDelta delta = prismContext.deltaFor(ShadowType.class) .property(ItemPath.create(ShadowType.F_ATTRIBUTES, new ItemName(MidPointConstants.NS_RI, "roomNumber"))) - .replace("cabin") + .replace("cabin") .property(ItemPath.create(ShadowType.F_ATTRIBUTES, new ItemName(MidPointConstants.NS_RI, "businessCategory"))) - .add("capsize", "fighting") + .add("capsize", "fighting") .asObjectDelta(ACCOUNT_GUYBRUSH_MODIFY_DELETE_OID); try { @@ -911,10 +870,8 @@ public void test142ModifyObjectNotFoundAssignedAccount() throws Exception { */ @Test public void test144GetObjectNotFoundAssignedAccount() throws Exception { - final String TEST_NAME = "test144GetObjectNotFoundAssignedAccount"; - // GIVEN - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddShadowFromFile(ACCOUNT_HECTOR_FILE, parentResult); repoAddObjectFromFile(USER_HECTOR_NOT_FOUND_FILENAME, parentResult); @@ -923,7 +880,7 @@ public void test144GetObjectNotFoundAssignedAccount() throws Exception { UserAsserter.forUser(userBefore) .assertLinks(1) .links() - .link(ACCOUNT_HECTOR_OID); + .link(ACCOUNT_HECTOR_OID); Task task = taskManager.createTaskInstance(); @@ -935,7 +892,7 @@ public void test144GetObjectNotFoundAssignedAccount() throws Exception { UserAsserter.forUser(userAfter) .assertLinks(1) .links() - .link(ACCOUNT_HECTOR_OID); + .link(ACCOUNT_HECTOR_OID); PrismObject modifiedAccount = getShadowModel(ACCOUNT_HECTOR_OID); assertNotNull(modifiedAccount); @@ -951,10 +908,8 @@ public void test144GetObjectNotFoundAssignedAccount() throws Exception { */ @Test public void test150RecomputeUserAccountNotFound() throws Exception { - final String TEST_NAME = "test150RecomputeUserAccountNotFound"; - // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assignAccountToUser(USER_GUYBRUSH_OID, RESOURCE_OPENDJ_OID, null); @@ -1006,10 +961,8 @@ public void test150RecomputeUserAccountNotFound() throws Exception { */ @Test public void test152RecomputeUserAccountAndShadowNotFound() throws Exception { - final String TEST_NAME = "test152RecomputeUserAccountAndShadowNotFound"; - // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_GUYBRUSH_OID); @@ -1054,10 +1007,8 @@ public void test152RecomputeUserAccountAndShadowNotFound() throws Exception { @Test public void test159DeleteUSerGuybrush() throws Exception { - final String TEST_NAME = "test159DeleteUSerGuybrush"; - // GIVEN - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_GUYBRUSH_OID); @@ -1084,7 +1035,6 @@ public void test159DeleteUSerGuybrush() throws Exception { @Test public void test200StopOpenDj() throws Exception { - final String TEST_NAME = "test200StopOpenDj"; openDJController.stop(); assertEquals("Resource is running", false, EmbeddedUtils.isRunning()); @@ -1092,17 +1042,14 @@ public void test200StopOpenDj() throws Exception { @Test public void test210AddObjectCommunicationProblem() throws Exception { - final String TEST_NAME = "test210AddObjectCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = task.getResult(); repoAddObjectFromFile(USER_E_FILENAME, parentResult); - assertUser(USER_E_OID, TEST_NAME).assertLinks(0); - + assertUser(USER_E_OID, getTestNameShort()).assertLinks(0); XMLGregorianCalendar lastRequestStartTs = clock.currentTimeXMLGregorianCalendar(); assignAccount(UserType.class, USER_E_OID, RESOURCE_OPENDJ_OID, "internal", task, parentResult); @@ -1117,7 +1064,7 @@ public void test210AddObjectCommunicationProblem() throws Exception { String shadowEOid = getLinkRefOid(USER_E_OID, RESOURCE_OPENDJ_OID); assertRepoShadow(shadowEOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + " Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsNotExists() .assertNotDead() @@ -1126,19 +1073,19 @@ public void test210AddObjectCommunicationProblem() throws Exception { .assertNoPrimaryIdentifierValue() .assertNoLegacyConsistency() .attributes() - .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) + .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() .display() .assertAdd(); @@ -1162,7 +1109,7 @@ public void test212AddModifyObjectCommunicationProblem() throws Exception { //WHEN ObjectDelta delta = prismContext.deltaFactory() .object() - .createModificationAddProperty(ShadowType.class, accountOid, createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER), "emp4321"); + .createModificationAddProperty(ShadowType.class, accountOid, createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER), "emp4321"); delta.addModificationReplaceProperty(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME), "eeeee"); when(); @@ -1182,36 +1129,34 @@ public void test212AddModifyObjectCommunicationProblem() throws Exception { .assertNoPrimaryIdentifierValue() .assertNoLegacyConsistency() .attributes() - .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) + .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) .end() .pendingOperations().assertOperations(2) - .addOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertAttemptNumber(2) - .delta() - .display() - .end() - .end() - .modifyOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .end() + .addOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertAttemptNumber(2) + .delta() + .display() + .end() + .end() + .modifyOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .end() .end() .end() .display(); - - // checkPostponedAccountWithAttributes(accountOid, "e", "Jackkk", "e", "e", "emp4321", FailedOperationTypeType.ADD, false, task, parentResult); } @@ -1225,7 +1170,7 @@ public void test214ModifyObjectCommunicationProblem() throws Exception { // GIVEN openDJController.assumeStopped(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); String accountOid = assertUserOneAccountRef(USER_JACK_OID); @@ -1251,23 +1196,22 @@ public void test214ModifyObjectCommunicationProblem() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertModify(); - + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertModify(); assertModelShadowFutureNoFetch(ACCOUNT_JACKIE_OID) .display() @@ -1275,9 +1219,9 @@ public void test214ModifyObjectCommunicationProblem() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jackkk") - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "emp4321") - .end() + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Jackkk") + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "emp4321") + .end() .assertIsExists() .end(); } @@ -1310,23 +1254,22 @@ public void test220DeleteObjectCommunicationProblem() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertDelete(); - + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertDelete(); // clockForward("PT20M"); // assertNoModelShadowFuture(ACCOUNT_DENIELS_OID); @@ -1339,7 +1282,7 @@ public void test230GetAccountCommunicationProblem() throws Exception { // GIVEN openDJController.assumeStopped(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); ShadowType account = modelService.getObject(ShadowType.class, ACCOUNT_DENIELS_OID, null, null, result).asObjectable(); @@ -1352,16 +1295,16 @@ public void test230GetAccountCommunicationProblem() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .delta() - .display() - .assertDelete(); + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .delta() + .display() + .assertDelete(); // clockForward("PT20M"); // assertNoModelShadowFuture(ACCOUNT_DENIELS_OID); @@ -1369,12 +1312,12 @@ public void test230GetAccountCommunicationProblem() throws Exception { } @Test - public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception{ + public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception { final String TEST_NAME = "test240AddObjectCommunicationProblemAlreadyExists"; // GIVEN openDJController.assumeRunning(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); Entry entry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILE); Entry searchResult = openDJController.searchByUid("elaine"); @@ -1421,21 +1364,21 @@ public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception .assertNoPrimaryIdentifierValue() .assertNoLegacyConsistency() .attributes() - .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) - .end() + .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) + .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertAdd(); + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertAdd(); //check futurized // checkPostponedAccountWithAttributes(shadowOid, "elaine", "Elaine", "Marley", "Elaine Marley", FailedOperationTypeType.ADD, false, task, parentResult); @@ -1447,7 +1390,7 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { // GIVEN openDJController.assumeStopped(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); assertUser(USER_JACK_OID, "User before") .assertLinks(1); @@ -1456,17 +1399,17 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { PropertyDelta fullNameDelta = prismContext.deltaFactory() .property() - .createModificationReplaceProperty(UserType.F_FULL_NAME, getUserDefinition(), new PolyString("jackNew2")); + .createModificationReplaceProperty(UserType.F_FULL_NAME, getUserDefinition(), new PolyString("jackNew2")); modifications.add(fullNameDelta); PropertyDelta enabledDelta = prismContext.deltaFactory() .property() - .createModificationAddProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getUserDefinition(), ActivationStatusType.ENABLED); + .createModificationAddProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getUserDefinition(), ActivationStatusType.ENABLED); modifications.add(enabledDelta); ObjectDelta objectDelta = prismContext.deltaFactory() .object() - .createModifyDelta(USER_JACKIE_OID, modifications, UserType.class); + .createModifyDelta(USER_JACKIE_OID, modifications, UserType.class); Task task = taskManager.createTaskInstance(); XMLGregorianCalendar lastRequestStartTs = clock.currentTimeXMLGregorianCalendar(); @@ -1489,23 +1432,22 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertModify(); - + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertModify(); assertModelShadowFutureNoFetch(shadowOid) .display() @@ -1514,14 +1456,11 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { .assertNoLegacyConsistency() .assertAdministrativeStatus(ActivationStatusType.ENABLED) .attributes() - .assertValue(LDAP_ATTRIBUTE_CN, "jackNew2") + .assertValue(LDAP_ATTRIBUTE_CN, "jackNew2") .end() .assertIsExists() .end(); - - - } @Test @@ -1530,7 +1469,7 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception // GIVEN openDJController.assumeStopped(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); assertUser(USER_JACKIE_OID, "User before") .assertLinks(1) @@ -1541,17 +1480,17 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception PropertyDelta fullNameDelta = prismContext.deltaFactory() .property() - .createModificationReplaceProperty(UserType.F_FULL_NAME, getUserDefinition(), new PolyString("jackNew2a")); + .createModificationReplaceProperty(UserType.F_FULL_NAME, getUserDefinition(), new PolyString("jackNew2a")); modifications.add(fullNameDelta); PropertyDelta givenNameDelta = prismContext.deltaFactory() .property() - .createModificationReplaceProperty(UserType.F_GIVEN_NAME, getUserDefinition(), new PolyString("jackNew2a")); + .createModificationReplaceProperty(UserType.F_GIVEN_NAME, getUserDefinition(), new PolyString("jackNew2a")); modifications.add(givenNameDelta); PropertyDelta enabledDelta = prismContext.deltaFactory() .property() - .createModificationAddProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getUserDefinition(), ActivationStatusType.ENABLED); + .createModificationAddProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getUserDefinition(), ActivationStatusType.ENABLED); modifications.add(enabledDelta); ObjectDelta objectDelta = prismContext.deltaFactory() @@ -1580,15 +1519,15 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception .assertNotDead() .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() - .pendingOperations() - .assertOperations(2) - .by() - .changeType(ChangeTypeType.MODIFY) - .executionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertAll(); + .pendingOperations() + .assertOperations(2) + .by() + .changeType(ChangeTypeType.MODIFY) + .executionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertAll(); // .modifyOperation() // .display() // .assertType(PendingOperationTypeType.RETRY) @@ -1617,8 +1556,6 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception // .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME)) // .end(); - - assertModelShadowFutureNoFetch(shadowOid) .display() .assertKind(ShadowKindType.ACCOUNT) @@ -1626,8 +1563,8 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception .assertNoLegacyConsistency() .assertAdministrativeStatus(ActivationStatusType.ENABLED) .attributes() - .assertValue(LDAP_ATTRIBUTE_CN, "jackNew2a") - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "jackNew2a") + .assertValue(LDAP_ATTRIBUTE_CN, "jackNew2a") + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "jackNew2a") .end() .assertIsExists() .end(); @@ -1646,7 +1583,7 @@ public void test260GetDiscoveryAddCommunicationProblem() throws Exception { // GIVEN openDJController.assumeStopped(); display("OpenDJ stopped"); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddObjectFromFile(USER_ANGELIKA_FILENAME, parentResult); @@ -1668,7 +1605,7 @@ public void test260GetDiscoveryAddCommunicationProblem() throws Exception { assertInProgress(parentResult); assertUser(USER_ANGELIKA_OID, "User after") - .assertLinks(1); + .assertLinks(1); String shadowOid = getLinkRefOid(USER_ANGELIKA_OID, RESOURCE_OPENDJ_OID); assertRepoShadow(shadowOid) @@ -1684,18 +1621,18 @@ public void test260GetDiscoveryAddCommunicationProblem() throws Exception { .assertAttributes(LDAP_ATTRIBUTE_DN, LDAP_ATTRIBUTE_UID) .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertAdd(); + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertAdd(); //start openDJ openDJController.start(); //and set the resource availability status to UP @@ -1717,7 +1654,7 @@ public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { //prepare user repoAddObjectFromFile(USER_ALICE_FILENAME, parentResult); assertUser(USER_ALICE_OID, "User before") - .assertLinks(0); + .assertLinks(0); //and add account to the user while resource is UP assignAccountToUser(USER_ALICE_OID, RESOURCE_OPENDJ_OID, "internal"); @@ -1744,24 +1681,23 @@ public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { // We will get that only when create operation is successful. .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() - .end() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() + .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertModify() - .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); - + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertModify() + .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); //start openDJ openDJController.start(); @@ -1779,22 +1715,22 @@ public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { ShadowAsserter.forShadow(shadowAfter) .attributes() - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "44332") + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "44332") .end() .pendingOperations() - .singleOperation() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.IN_PROGRESS) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(2) - .assertLastAttemptTimestamp(lastAttemptStartTs, lastAttemptEndTs) - .delta() - .display() - .assertModify() - .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); + .singleOperation() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.IN_PROGRESS) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(2) + .assertLastAttemptTimestamp(lastAttemptStartTs, lastAttemptEndTs) + .delta() + .display() + .assertModify() + .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); } @Test @@ -1807,7 +1743,7 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E OperationResult parentResult = task.getResult(); assertUser(USER_ALICE_OID, "User before") - .assertLinks(1); + .assertLinks(1); String shadowOid = getLinkRefOid(USER_ALICE_OID, RESOURCE_OPENDJ_OID); // WHEN (down) @@ -1826,41 +1762,41 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E // We will get that only when create operation is successful. .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() .pendingOperations() - .assertOperations(2) - .by() - .executionStatus(PendingOperationExecutionStatusType.EXECUTING) - .find() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertModify() - .assertHasModification(SchemaConstants.PATH_PASSWORD_VALUE) - .end() - .end() - .by() - .executionStatus(PendingOperationExecutionStatusType.COMPLETED) - .find() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) - .assertResultStatus(OperationResultStatusType.SUCCESS) - .assertAttemptNumber(2) - .delta() - .display() - .assertModify() - .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER));; - + .assertOperations(2) + .by() + .executionStatus(PendingOperationExecutionStatusType.EXECUTING) + .find() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertModify() + .assertHasModification(SchemaConstants.PATH_PASSWORD_VALUE) + .end() + .end() + .by() + .executionStatus(PendingOperationExecutionStatusType.COMPLETED) + .find() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertExecutionStatus(PendingOperationExecutionStatusType.COMPLETED) + .assertResultStatus(OperationResultStatusType.SUCCESS) + .assertAttemptNumber(2) + .delta() + .display() + .assertModify() + .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); + ; //start openDJ openDJController.start(); @@ -1873,8 +1809,8 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E .assertNotDead() .display() .attributes() - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "44332") - .assertHasPrimaryIdentifier(); + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER, "44332") + .assertHasPrimaryIdentifier(); assertUser(USER_ALICE_OID, "User after") .assertPassword("DEADmenTELLnoTALES"); @@ -1918,27 +1854,26 @@ public void test265ModifyUserPasswordCommunicationProblemRecon() throws Exceptio // We will get that only when create operation is successful. .assertNoLegacyConsistency() .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() .end() - .pendingOperations() - .assertOperations(3) - .by() - .executionStatus(PendingOperationExecutionStatusType.EXECUTING) - .find() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .assertResultStatus(OperationResultStatusType.FATAL_ERROR) - .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) - .assertAttemptNumber(1) - .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) - .delta() - .display() - .assertModify() - .assertHasModification(SchemaConstants.PATH_PASSWORD_VALUE); - + .pendingOperations() + .assertOperations(3) + .by() + .executionStatus(PendingOperationExecutionStatusType.EXECUTING) + .find() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertRequestTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .assertResultStatus(OperationResultStatusType.FATAL_ERROR) + .assertOperationStartTimestamp(lastRequestStartTs, lastRequestEndTs) + .assertAttemptNumber(1) + .assertLastAttemptTimestamp(lastRequestStartTs, lastRequestEndTs) + .delta() + .display() + .assertModify() + .assertHasModification(SchemaConstants.PATH_PASSWORD_VALUE); //start openDJ openDJController.start(); @@ -1968,7 +1903,7 @@ public void test270ModifyDiscoveryAddCommunicationProblem() throws Exception { // GIVEN openDJController.assumeStopped(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); // WHEN repoAddObjectFromFile(USER_BOB_NO_GIVEN_NAME_FILENAME, parentResult); @@ -1997,7 +1932,7 @@ public void test270ModifyDiscoveryAddCommunicationProblem() throws Exception { getShadowModelNoFetch(shadowOid); OperationResult modifyGivenNameResult = new OperationResult("execute changes -> modify user's given name"); - LOGGER.trace("execute changes -> modify user's given name"); + logger.trace("execute changes -> modify user's given name"); modifyObjectAddProperty(UserType.class, USER_BOB_NO_GIVEN_NAME_OID, UserType.F_GIVEN_NAME, task, modifyGivenNameResult, new PolyString("Bob")); modifyGivenNameResult.computeStatus(); @@ -2010,20 +1945,20 @@ public void test270ModifyDiscoveryAddCommunicationProblem() throws Exception { .assertNotDead() .assertResource(RESOURCE_OPENDJ_OID) .attributes() - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Bob") - .assertValue(LDAP_ATTRIBUTE_UID, "bob") - .assertValue(LDAP_ATTRIBUTE_CN, "Bob Dylan") - .assertValue(LDAP_ATTRIBUTE_SN, "Dylan"); + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "Bob") + .assertValue(LDAP_ATTRIBUTE_UID, "bob") + .assertValue(LDAP_ATTRIBUTE_CN, "Bob Dylan") + .assertValue(LDAP_ATTRIBUTE_SN, "Dylan"); } @Test - public void test280ModifyObjectCommunicationProblemWeakMapping() throws Exception{ + public void test280ModifyObjectCommunicationProblemWeakMapping() throws Exception { final String TEST_NAME = "test280ModifyObjectCommunicationProblemWeakMapping"; // GIVEN openDJController.assumeRunning(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddObjectFromFile(USER_JOHN_WEAK_FILENAME, parentResult); assertUser(USER_JOHN_WEAK_OID, "User before") @@ -2042,37 +1977,35 @@ public void test280ModifyObjectCommunicationProblemWeakMapping() throws Exceptio .assertIsExists() .assertNotDead() .attributes() - .assertValue(LDAP_ATTRIBUTE_UID, "john") - .assertValue(LDAP_ATTRIBUTE_SN, "weak") - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "john") - .assertValue(LDAP_ATTRIBUTE_CN, "john weak") - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); + .assertValue(LDAP_ATTRIBUTE_UID, "john") + .assertValue(LDAP_ATTRIBUTE_SN, "weak") + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "john") + .assertValue(LDAP_ATTRIBUTE_CN, "john weak") + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); //stop opendj and try to modify employeeType (weak mapping) openDJController.stop(); - LOGGER.info("start modifying user - account with weak mapping after stopping opendj."); + logger.info("start modifying user - account with weak mapping after stopping opendj."); modifyUserReplace(USER_JOHN_WEAK_OID, UserType.F_EMPLOYEE_TYPE, task, parentResult, "boss"); assertModelShadowFutureNoFetch(shadowOid) .pendingOperations() - .assertOperations(0); - + .assertOperations(0); // // TODO: [RS] not 100% sure about this. But if you do not expect an error you should not set doNotDiscovery. Server is still not running. // checkNormalizedShadowBasic(accountOid, "john", true, null, task, parentResult); // checkNormalizedShadowBasic(accountOid, "john", true, SelectorOptions.createCollection(GetOperationOptions.createDoNotDiscovery()), task, parentResult); } - @Test public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws Exception { final String TEST_NAME = "test282ModifyObjectCommunicationProblemWeakAndStrongMapping"; // GIVEN openDJController.assumeRunning(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddObjectFromFile(USER_DONALD_FILENAME, parentResult); @@ -2093,26 +2026,24 @@ public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws .assertIsExists() .assertNotDead() .attributes() - .assertValue(LDAP_ATTRIBUTE_UID, "donald") - .assertValue(LDAP_ATTRIBUTE_SN, "trump") - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "donald") - .assertValue(LDAP_ATTRIBUTE_CN, "donald trump") - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); - + .assertValue(LDAP_ATTRIBUTE_UID, "donald") + .assertValue(LDAP_ATTRIBUTE_SN, "trump") + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "donald") + .assertValue(LDAP_ATTRIBUTE_CN, "donald trump") + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); //stop opendj and try to modify employeeType (weak mapping) openDJController.stop(); - - LOGGER.info("start modifying user - account with weak mapping after stopping opendj."); + logger.info("start modifying user - account with weak mapping after stopping opendj."); PropertyDelta employeeTypeDelta = prismContext.deltaFactory() .property() - .createModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, getUserDefinition(), "boss"); + .createModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, getUserDefinition(), "boss"); ObjectDelta userDelta = prismContext.deltaFactory() .object() - .createModificationReplaceProperty(UserType.class, USER_DONALD_OID, UserType.F_GIVEN_NAME, new PolyString("don")); + .createModificationReplaceProperty(UserType.class, USER_DONALD_OID, UserType.F_GIVEN_NAME, new PolyString("don")); userDelta.addModification(employeeTypeDelta); XMLGregorianCalendar lastRequestStartTs = clock.currentTimeXMLGregorianCalendar(); @@ -2123,13 +2054,13 @@ public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws .assertNotDead() .assertNoLegacyConsistency() .pendingOperations() - .singleOperation() - .display() - .assertAttemptNumber(1) - .delta() - .assertModify() - .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME)) - .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)); + .singleOperation() + .display() + .assertAttemptNumber(1) + .delta() + .assertModify() + .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME)) + .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)); } @@ -2139,7 +2070,7 @@ public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { // GIVEN openDJController.assumeRunning(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); assertUser(USER_DONALD_OID, "User before") .assertLinks(1); @@ -2151,13 +2082,13 @@ public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { .assertNotDead() .assertNoLegacyConsistency() .pendingOperations() - .singleOperation() - .display() - .assertAttemptNumber(1) - .delta() - .assertModify() - .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME)) - .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)); + .singleOperation() + .display() + .assertAttemptNumber(1) + .delta() + .assertModify() + .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME)) + .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)); //WHEN when(); @@ -2167,8 +2098,8 @@ public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { then(); assertModelShadow(shadowOid) .attributes() - .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "don") - .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); + .assertValue(LDAP_ATTRIBUTE_GIVENNAME, "don") + .assertValue(LDAP_ATTRIBUTE_EMPLOYEE_TYPE, "manager"); } @@ -2176,7 +2107,7 @@ public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Exception { final String TEST_NAME = "test284ModifyObjectAssignToGroupCommunicationProblem"; Task task = taskManager.createTaskInstance(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); // GIVEN openDJController.addEntriesFromLdifFile(LDIF_CREATE_ADMINS_GROUP_FILE); @@ -2184,14 +2115,14 @@ public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Except SearchResultList> shadows = modelService.searchObjects(ShadowType.class, filter, null, task, parentResult); for (PrismObject shadow : shadows) { - LOGGER.info("SHADOW ===> {}", shadow.debugDump() ); + logger.info("SHADOW ===> {}", shadow.debugDump()); } // WHEN openDJController.assumeStopped(); assertUser(USER_DONALD_OID, "User before") - .assertLinks(1); + .assertLinks(1); String shadowOid = getLinkRefOid(USER_DONALD_OID, RESOURCE_OPENDJ_OID); @@ -2202,14 +2133,13 @@ public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Except adminRoleAssignment.setTargetRef(ObjectTypeUtil.createObjectRef(ROLE_LDAP_ADMINS_OID, ObjectTypes.ROLE)); ObjectDelta delta = prismContext.deltaFactory() .object() - .createModificationAddContainer(UserType.class, USER_DONALD_OID, UserType.F_ASSIGNMENT, adminRoleAssignment); + .createModificationAddContainer(UserType.class, USER_DONALD_OID, UserType.F_ASSIGNMENT, adminRoleAssignment); delta.addModification(prismContext.deltaFactory() .property() - .createModificationReplaceProperty(UserType.F_GIVEN_NAME, getUserDefinition(), new PolyString("donalld"))); + .createModificationReplaceProperty(UserType.F_GIVEN_NAME, getUserDefinition(), new PolyString("donalld"))); executeChanges(delta, null, task, parentResult); - // Get user's account with noFetch option - changes shouldn't be applied, bud should be still saved in shadow assertModelShadowNoFetch(shadowOid) .assertIsExists() @@ -2217,16 +2147,15 @@ public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Except .assertIntent("internal") .assertKind() .pendingOperations() - .by() - .executionStatus(PendingOperationExecutionStatusType.EXECUTING) - .find() - .display() - .assertType(PendingOperationTypeType.RETRY) - .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) - .delta() - .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)) - .assertHasModification(ShadowType.F_ASSOCIATION); - + .by() + .executionStatus(PendingOperationExecutionStatusType.EXECUTING) + .find() + .display() + .assertType(PendingOperationTypeType.RETRY) + .assertExecutionStatus(PendingOperationExecutionStatusType.EXECUTING) + .delta() + .assertNoModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_TYPE)) + .assertHasModification(ShadowType.F_ASSOCIATION); //THEN openDJController.assumeRunning(); @@ -2242,16 +2171,14 @@ public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Except //TODO: check on user if it was processed successfully (add this check also to previous (30) test.. } - - //TODO: enable after notify failure will be implemented.. @Test(enabled = false) - public void test400GetDiscoveryAddCommunicationProblemAlreadyExists() throws Exception{ + public void test400GetDiscoveryAddCommunicationProblemAlreadyExists() throws Exception { final String TEST_NAME = "test400GetDiscoveryAddCommunicationProblemAlreadyExists"; // GIVEN openDJController.assumeStopped(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); repoAddObjectFromFile(USER_DISCOVERY_FILENAME, parentResult); @@ -2303,7 +2230,6 @@ public void test500AddUserMorganWithAssignment() throws Exception { Entry entry = openDJController.addEntryFromLdifFile(LDIF_MORGAN_FILE); display("Entry from LDIF", entry); - // WHEN when(); addObject(USER_MORGAN_FILE, task, result); @@ -2331,7 +2257,6 @@ public void test500AddUserMorganWithAssignment() throws Exception { assertShadowModel(accountModel, accountOid, "uid=morgan,ou=people,dc=example,dc=com", resourceTypeOpenDjrepo, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); } - /** * Adding a user (morgan) that has an OpenDJ assignment. But the equivalent account already exists on * OpenDJ and there is also corresponding shadow in the repo. The account should be linked. @@ -2389,7 +2314,6 @@ public void test501AddUserChuckWithAssignment() throws Exception { // TODO: check OpenDJ Account } - /** * Assigning accoun to user, account with the same identifier exist on the resource and there is also shadow in the repository. The account should be linked. */ @@ -2451,7 +2375,7 @@ public void test502AssignAccountToHerman() throws Exception { } /** - * Unlink account morgan, delete shadow and remove assignmnet from user morgan - preparation for the next test + * Unlink account morgan, delete shadow and remove assignmnet from user morgan - preparation for the next test */ @Test public void test510UnlinkAndUnassignAccountMorgan() throws Exception { @@ -2481,7 +2405,7 @@ public void test510UnlinkAndUnassignAccountMorgan() throws Exception { USER_MORGAN_OID, UserType.F_ASSIGNMENT, user.findContainer(UserType.F_ASSIGNMENT).getValue().clone()); deltas = MiscSchemaUtil.createCollection(userDelta); - // WHEN + // WHEN when(); modelService.executeChanges(deltas, null, task, result); @@ -2500,27 +2424,27 @@ public void test510UnlinkAndUnassignAccountMorgan() throws Exception { // Check shadow String accountOid = linkRef.getOid(); try { - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "uid=morgan,ou=people,dc=example,dc=com", resourceTypeOpenDjrepo); - fail("Unexpected shadow in repo. Shadow mut not exist"); - } catch (ObjectNotFoundException ex){ + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "uid=morgan,ou=people,dc=example,dc=com", resourceTypeOpenDjrepo); + fail("Unexpected shadow in repo. Shadow mut not exist"); + } catch (ObjectNotFoundException ex) { //this is expected..shadow must not exist in repo } // Check account try { - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "uid=morgan,ou=people,dc=example,dc=com", resourceTypeOpenDjrepo); - fail("Unexpected shadow in repo. Shadow mut not exist"); - } catch (ObjectNotFoundException ex){ + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "uid=morgan,ou=people,dc=example,dc=com", resourceTypeOpenDjrepo); + fail("Unexpected shadow in repo. Shadow mut not exist"); + } catch (ObjectNotFoundException ex) { //this is expected..shadow must not exist in repo } // TODO: check OpenDJ Account } - /** * assign account to the user morgan. Account with the same 'uid' (not dn, nut other secondary identifier already exists) * account should be linked to the user. + * * @throws Exception */ @Test @@ -2570,7 +2494,6 @@ public void test511AssignAccountMorgan() throws Exception { when(); modelService.executeChanges(deltas, null, task, result); - // THEN then(); result.computeStatus(); @@ -2596,7 +2519,6 @@ public void test511AssignAccountMorgan() throws Exception { // TODO: check OpenDJ Account } - @Test public void test600DeleteUserAlice() throws Exception { String TEST_NAME = "test600DeleteUserAlice"; @@ -2613,7 +2535,7 @@ public void test600DeleteUserAlice() throws Exception { try { modelService.getObject(UserType.class, USER_ALICE_OID, null, task, parentResult); fail("Expected object not found error, but haven't got one. Something went wrong while deleting user alice"); - } catch (ObjectNotFoundException ex){ + } catch (ObjectNotFoundException ex) { //this is expected } @@ -2625,7 +2547,7 @@ public void test601GetDiscoveryModifyCommunicationProblemDirectAccount() throws String TEST_NAME = "test601GetDiscoveryModifyCommunicationProblemDirectAccount"; openDJController.assumeRunning(); - OperationResult parentResult = createOperationalResult(); + OperationResult parentResult = createOperationResult(); //prepare user repoAddObjectFromFile(USER_ALICE_FILENAME, parentResult); @@ -2648,7 +2570,7 @@ public void test601GetDiscoveryModifyCommunicationProblemDirectAccount() throws //WHEN ObjectDelta delta = prismContext.deltaFactory() .object() - .createModificationAddProperty(ShadowType.class, accountOid, createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER), "emp4321"); + .createModificationAddProperty(ShadowType.class, accountOid, createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER), "emp4321"); delta.addModificationReplaceProperty(createAttributePath(LDAP_ATTRIBUTE_GIVENNAME), "Aliceeee"); executeChanges(delta, null, task, parentResult); @@ -2693,14 +2615,13 @@ public void test800Reconciliation() throws Exception { UserType userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result).asObjectable(); display("Jack before", userJack); - - LOGGER.info("start running task"); + logger.info("start running task"); // WHEN repoAddObjectFromFile(TASK_OPENDJ_RECONCILIATION_FILE, result); verbose = true; long started = System.currentTimeMillis(); waitForTaskNextRunAssertSuccess(TASK_OPENDJ_RECONCILIATION_OID, false, 120000); - LOGGER.info("Reconciliation task run took {} seconds", (System.currentTimeMillis()-started)/1000L); + logger.info("Reconciliation task run took {} seconds", (System.currentTimeMillis() - started) / 1000L); // THEN @@ -2720,14 +2641,12 @@ public void test800Reconciliation() throws Exception { assertFalse(identifiers.isEmpty()); assertEquals(1, identifiers.size()); - // check if the account was modified during reconciliation process String jackAccountOid = assertUserOneAccountRef(USER_JACK_OID); ShadowType modifiedAccount = checkNormalizedShadowBasic(jackAccountOid, "jack", true, SelectorOptions.createCollection(GetOperationOptions.createDoNotDiscovery()), null, result); assertAttribute(modifiedAccount, "givenName", "Jackkk"); assertAttribute(modifiedAccount, "employeeNumber", "emp4321"); - // check if the account was marked as dead during the reconciliation process assertRepoShadow(ACCOUNT_DENIELS_OID) .assertDead(); @@ -2737,32 +2656,31 @@ public void test800Reconciliation() throws Exception { .links(); ShadowReferenceAsserter notDeadShadow = linksAsserter.by() - .dead(false) - .find(); - + .dead(false) + .find(); assertModelShadow(notDeadShadow.getOid()) - .display() - .attributes() - .assertHasPrimaryIdentifier() - .assertHasSecondaryIdentifier() - .end() - .end(); + .display() + .attributes() + .assertHasPrimaryIdentifier() + .assertHasSecondaryIdentifier() + .end() + .end(); ShadowReferenceAsserter deadShadow = linksAsserter.by() - .dead(true) - .find(); + .dead(true) + .find(); assertModelShadowNoFetch(deadShadow.getOid()) - .display() - .attributes() - .assertNoPrimaryIdentifier() - .end() - .pendingOperations() - .singleOperation() - .display() - .delta() - .assertAdd(); + .display() + .attributes() + .assertNoPrimaryIdentifier() + .end() + .pendingOperations() + .singleOperation() + .display() + .delta() + .assertAdd(); accountOid = assertUserOneAccountRef(USER_JACKIE_OID); ShadowType jack2Shadow = checkNormalizedShadowBasic(accountOid, "jack2", true, SelectorOptions.createCollection(GetOperationOptions.createDoNotDiscovery()), null, result); @@ -2780,19 +2698,19 @@ public void test801TestReconciliationRename() throws Exception { Task task = getTestTask(); final OperationResult result = task.getResult(); - LOGGER.info("starting rename"); + logger.info("starting rename"); openDJController.executeRenameChange(LDIF_MODIFY_RENAME_FILE); - LOGGER.info("rename ended"); + logger.info("rename ended"); // Entry res = openDJController.searchByUid("e"); // LOGGER.info("E OBJECT AFTER RENAME " + res.toString()); - LOGGER.info("start running task"); + logger.info("start running task"); // WHEN long started = System.currentTimeMillis(); repoAddObjectFromFile(TASK_OPENDJ_RECONCILIATION_FILE, result); waitForTaskFinish(TASK_OPENDJ_RECONCILIATION_OID, false, 120000); - LOGGER.info("Reconciliation task run took {} seconds", (System.currentTimeMillis()-started)/1000L); + logger.info("Reconciliation task run took {} seconds", (System.currentTimeMillis() - started) / 1000L); // THEN @@ -2812,7 +2730,6 @@ public void test801TestReconciliationRename() throws Exception { assertFalse(identifiers.isEmpty()); assertEquals(1, identifiers.size()); - ResourceAttribute icfNameAttr = attributeContainer.findAttribute(getOpenDjSecondaryIdentifierQName()); assertEquals("Wrong secondary indetifier.", "uid=e123,ou=people,dc=example,dc=com", icfNameAttr.getRealValue()); @@ -2899,7 +2816,7 @@ private void checkOpenResourceConfiguration(PrismObject resource, .findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); assertNotNull("No configuration properties container in " + resource + " from " + source, configPropsContainer); - Collection> configProps = configPropsContainer.getValue().getItems(); + Collection> configProps = configPropsContainer.getValue().getItems(); assertEquals("Wrong number of config properties in " + resource + " from " + source, numConfigProps, configProps.size()); PrismProperty credentialsProp = configPropsContainer.findProperty(new ItemName( @@ -2916,7 +2833,7 @@ private void checkOpenResourceConfiguration(PrismObject resource, assertNotNull("No credentials property value in " + resource + " from " + source, credentialsPropertyValue); Object rawElement = credentialsPropertyValue.getRawElement(); - } + } private UserType testAddUserToRepo(String displayMessage, String fileName, String userOid) throws IOException, ObjectNotFoundException, SchemaException, EncryptionException, @@ -2949,8 +2866,7 @@ private UserType testAddUserToRepo(String displayMessage, String fileName, Strin return userType; } - - private String assertUserOneAccountRef(String userOid) throws Exception{ + private String assertUserOneAccountRef(String userOid) throws Exception { OperationResult parentResult = new OperationResult("getObject from repo"); PrismObject repoUser = repositoryService.getObject(UserType.class, userOid, @@ -2963,7 +2879,7 @@ private String assertUserOneAccountRef(String userOid) throws Exception{ return assertOneAccountRef(repoUser); } - private String assertOneAccountRef(PrismObject user) throws Exception{ + private String assertOneAccountRef(PrismObject user) throws Exception { UserType repoUserType = user.asObjectable(); display("User (repository)", user); @@ -2975,22 +2891,22 @@ private String assertOneAccountRef(PrismObject user) throws Exception{ return accountRef.getOid(); } - private void assertUserNoAccountRef(String userOid, OperationResult parentResult) throws Exception{ + private void assertUserNoAccountRef(String userOid, OperationResult parentResult) throws Exception { PrismObject user = repositoryService .getObject(UserType.class, userOid, null, parentResult); assertEquals(0, user.asObjectable().getLinkRef().size()); } - private QName getOpenDjSecondaryIdentifierQName() { + private QName getOpenDjSecondaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); } - private String checkUser(String userOid, Task task, OperationResult parentResult) throws Exception{ + private String checkUser(String userOid, Task task, OperationResult parentResult) throws Exception { PrismObject user = modelService.getObject(UserType.class, userOid, null, task, parentResult); return checkUser(user); } - private String checkUser(PrismObject user){ + private String checkUser(PrismObject user) { assertNotNull("User must not be null", user); UserType userType = user.asObjectable(); assertEquals("User must have one link ref, ", 1, userType.getLinkRef().size()); @@ -3001,7 +2917,7 @@ private String checkUser(PrismObject user){ return accountOid; } - private void assertAttributes(ShadowType shadow, String uid, String givenName, String sn, String cn){ + private void assertAttributes(ShadowType shadow, String uid, String givenName, String sn, String cn) { assertAttribute(shadow, "uid", uid); if (givenName != null) { assertAttribute(shadow, "givenName", givenName); @@ -3012,7 +2928,7 @@ private void assertAttributes(ShadowType shadow, String uid, String givenName, S assertAttribute(shadow, "cn", cn); } - private ShadowType checkPostponedAccountBasic(PrismObject failedAccount, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception{ + private ShadowType checkPostponedAccountBasic(PrismObject failedAccount, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception { display("Repository shadow (postponed operation expected)", failedAccount); assertNotNull("Shadow must not be null", failedAccount); ShadowType failedAccountType = failedAccount.asObjectable(); @@ -3031,14 +2947,14 @@ private ShadowType checkPostponedAccountBasic(PrismObject failedAcco return failedAccountType; } - private ShadowType checkPostponedAccountBasic(String accountOid, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception{ + private ShadowType checkPostponedAccountBasic(String accountOid, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception { PrismObject faieldAccount = repositoryService.getObject(ShadowType.class, accountOid, null, parentResult); return checkPostponedAccountBasic(faieldAccount, failedOperation, modify, parentResult); } - private Collection> createDeltas(Class type, File requestFile, String objectOid) throws IOException, SchemaException, JAXBException{ + private Collection> createDeltas(Class type, File requestFile, String objectOid) throws IOException, SchemaException, JAXBException { - try{ + try { ObjectDeltaType objectChange = unmarshallValueFromFile(requestFile, ObjectDeltaType.class); objectChange.setOid(objectOid); @@ -3047,8 +2963,8 @@ private Collection> createDeltas(Class type, F Collection> deltas = MiscSchemaUtil.createCollection(delta); return deltas; - } catch (Exception ex){ - LOGGER.error("ERROR while unmarshalling: {}", ex); + } catch (Exception ex) { + logger.error("ERROR while unmarshalling: {}", ex); throw ex; } @@ -3063,13 +2979,13 @@ private void modifyResourceAvailabilityStatus(AvailabilityStatusType status, Ope repositoryService.modifyObject(ResourceType.class, resourceTypeOpenDjrepo.getOid(), modifications, parentResult); } - private ShadowType checkNormalizedShadowWithAttributes(String accountOid, String uid, String givenName, String sn, String cn, boolean modify, Task task, OperationResult parentResult) throws Exception{ + private ShadowType checkNormalizedShadowWithAttributes(String accountOid, String uid, String givenName, String sn, String cn, boolean modify, Task task, OperationResult parentResult) throws Exception { ShadowType resourceAccount = checkNormalizedShadowBasic(accountOid, uid, modify, null, task, parentResult); assertAttributes(resourceAccount, uid, givenName, sn, cn); return resourceAccount; } - private ShadowType checkNormalizedShadowBasic(String accountOid, String name, boolean modify, Collection> options,Task task, OperationResult parentResult) throws Exception{ + private ShadowType checkNormalizedShadowBasic(String accountOid, String name, boolean modify, Collection> options, Task task, OperationResult parentResult) throws Exception { PrismObject account = modelService.getObject(ShadowType.class, accountOid, options, task, parentResult); assertNotNull(account); ShadowType accountType = account.asObjectable(); @@ -3089,11 +3005,11 @@ private ShadowType checkNormalizedShadowBasic(String accountOid, String name, bo } - protected void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { + protected void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } - protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { + protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestManyThreads.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestManyThreads.java index f8d69387c9b..76552590c3a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestManyThreads.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestManyThreads.java @@ -6,6 +6,16 @@ */ package com.evolveum.midpoint.testing.story; +import static org.testng.AssertJUnit.*; + +import java.io.File; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummyResource; import com.evolveum.midpoint.model.impl.lens.LensUtil; @@ -22,30 +32,17 @@ import com.evolveum.midpoint.test.ThreadTestExecutor; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; - -import static org.testng.AssertJUnit.*; /** * Tests behavior of selected components when executing in large number of threads. */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestManyThreads extends AbstractStoryTest { public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "threads"); - private static final Trace LOGGER = TraceManager.getTrace(TestManyThreads.class); - private static final TestResource RESOURCE_DUMMY = new TestResource(TEST_DIR, "resource-dummy.xml", "be4d88ff-bbb7-45f2-91dc-4b0fc9a00ced"); @Autowired RepositoryCache repositoryCache; diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java index cdc4d95ee19..0d5f862cc95 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java @@ -7,15 +7,14 @@ package com.evolveum.midpoint.testing.story; import static org.testng.AssertJUnit.assertEquals; + import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -28,6 +27,7 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.MidPointConstants; @@ -47,19 +47,7 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectSearchStrategyType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SearchObjectExpressionEvaluatorType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; @@ -68,7 +56,7 @@ * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPlentyOfAssignments extends AbstractStoryTest { @@ -110,9 +98,6 @@ public class TestPlentyOfAssignments extends AbstractStoryTest { private static final int NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS = NUMBER_OF_GENERATED_DUMMY_ROLES; - private static final Trace LOGGER = TraceManager.getTrace(TestPlentyOfAssignments.class); - - private CountingInspector inspector; @Override @@ -126,20 +111,20 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti ObjectFactory objectFactory = new ObjectFactory(); generateRoles(NUMBER_OF_GENERATED_EMPTY_ROLES, "Empty Role %04d", GENERATED_EMPTY_ROLE_OID_FORMAT, null, initResult); generateRoles(NUMBER_OF_GENERATED_DUMMY_ROLES, "Dummy Role %04d", GENERATED_DUMMY_ROLE_OID_FORMAT, - (role,i) -> { + (role, i) -> { ItemPathType attrPath = new ItemPathType( ItemPath.create(new QName(RESOURCE_DUMMY_NS, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME))); JAXBElement evaluator = objectFactory.createValue(formatRum(i)); role - .beginInducement() + .beginInducement() .beginConstruction() - .resourceRef(RESOURCE_DUMMY_OID, ResourceType.COMPLEX_TYPE) - .kind(ShadowKindType.ACCOUNT) - .beginAttribute() - .ref(attrPath) - .beginOutbound() - .beginExpression() - .expressionEvaluator(evaluator); + .resourceRef(RESOURCE_DUMMY_OID, ResourceType.COMPLEX_TYPE) + .kind(ShadowKindType.ACCOUNT) + .beginAttribute() + .ref(attrPath) + .beginOutbound() + .beginExpression() + .expressionEvaluator(evaluator); }, initResult); inspector = new CountingInspector(); @@ -194,7 +179,7 @@ public void test100AddCheese() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Added cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); + display("Added cheese in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_CHEESE_ASSIGNMENTS) + "ms per assignment)"); PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); @@ -211,7 +196,6 @@ public void test100AddCheese() throws Exception { assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - @Test public void test110RecomputeCheese() throws Exception { final String TEST_NAME = "test110RecomputeCheese"; @@ -237,7 +221,7 @@ public void test110RecomputeCheese() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Recomputed cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); + display("Recomputed cheese in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_CHEESE_ASSIGNMENTS) + "ms per assignment)"); PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); @@ -281,7 +265,7 @@ public void test120CheesePreviewChanges() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Preview cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); + display("Preview cheese in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_CHEESE_ASSIGNMENTS) + "ms per assignment)"); PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); @@ -314,11 +298,10 @@ private void assertCheeseRoleMembershipRef(PrismObject cheese) { assertRoleMembershipRefs(cheese, NUMBER_OF_CHEESE_ASSIGNMENTS); } - /** * Create dummy groups that can be used for associationTargetSearch later on. * Create them from midPoint so they have shadows. - * + *

* MID-3938 #8 */ @Test @@ -338,17 +321,17 @@ public void test200DummyGroups() throws Exception { ObjectFactory objectFactory = new ObjectFactory(); ItemPath nameAttributePath = ItemPath.create(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME); - for (int i=0; i shadow = shadowDef.instantiate(); ShadowType shadowType = shadow.asObjectable(); shadowType - .resourceRef(RESOURCE_DUMMY_OID, ResourceType.COMPLEX_TYPE) - .objectClass(rOcDef.getTypeName()); + .resourceRef(RESOURCE_DUMMY_OID, ResourceType.COMPLEX_TYPE) + .objectClass(rOcDef.getTypeName()); ResourceAttributeContainer attributesContainer = ShadowUtil.getOrCreateAttributesContainer(shadow, rOcDef); ResourceAttribute nameAttribute = attributesContainer.findOrCreateAttribute(SchemaConstants.ICFS_NAME); String groupName = formatGroupName(i); nameAttribute.setRealValue(groupName); - display("Group shadow "+i, shadow); + display("Group shadow " + i, shadow); addObject(shadow, task, result); PrismObject role = roleDef.instantiate(); @@ -362,17 +345,17 @@ public void test200DummyGroups() throws Exception { associationTargetSearchType.setSearchStrategy(ObjectSearchStrategyType.IN_REPOSITORY); JAXBElement evaluator = objectFactory.createAssociationTargetSearch(associationTargetSearchType); roleType - .oid(generateRoleOid(GENERATED_DUMMY_GROUP_ROLE_OID_FORMAT, i)) - .name(String.format("Group role %04d", i)) - .beginInducement() + .oid(generateRoleOid(GENERATED_DUMMY_GROUP_ROLE_OID_FORMAT, i)) + .name(String.format("Group role %04d", i)) + .beginInducement() .beginConstruction() .resourceRef(RESOURCE_DUMMY_OID, ResourceType.COMPLEX_TYPE) .kind(ShadowKindType.ACCOUNT) .beginAssociation() - .ref(assPath) - .beginOutbound() - .beginExpression() - .expressionEvaluator(evaluator); + .ref(assPath) + .beginOutbound() + .beginExpression() + .expressionEvaluator(evaluator); try { IntegrationTestTools.displayXml("RRRRRRRRR group", role); } catch (SchemaException e) { @@ -421,7 +404,7 @@ public void test210AddBob() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Added bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); + display("Added bob in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); @@ -465,7 +448,7 @@ public void test212RecomputeBob() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Recomputed bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); + display("Recomputed bob in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); @@ -509,7 +492,7 @@ public void test2124ReconcileBob() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Reconciled bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); + display("Reconciled bob in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); @@ -576,7 +559,7 @@ public void test220AddAlice() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Added alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); + display("Added alice in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_GENERATED_DUMMY_GROUPS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); @@ -621,7 +604,7 @@ public void test222RecomputeAlice() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Recomputed alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); + display("Recomputed alice in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_GENERATED_DUMMY_GROUPS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); @@ -665,7 +648,7 @@ public void test224ReconcileAlice() throws Exception { long endMillis = System.currentTimeMillis(); assertSuccess(result); - display("Reconciled alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); + display("Reconciled alice in " + (endMillis - startMillis) + "ms (" + ((endMillis - startMillis) / NUMBER_OF_GENERATED_DUMMY_GROUPS) + "ms per assignment)"); PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); @@ -720,12 +703,12 @@ private void assertRoleMembershipRef(PrismObject user, String roleOidF private void assertRoleMembershipRef(PrismObject user, String roleOid, QName relation) { List roleMembershipRefs = user.asObjectable().getRoleMembershipRef(); - for (ObjectReferenceType roleMembershipRef: roleMembershipRefs) { + for (ObjectReferenceType roleMembershipRef : roleMembershipRefs) { if (ObjectTypeUtil.referenceMatches(roleMembershipRef, roleOid, RoleType.COMPLEX_TYPE, relation, prismContext)) { return; } } - fail("Cannot find membership of role "+roleOid+" ("+relation.getLocalPart()+") in "+user); + fail("Cannot find membership of role " + roleOid + " (" + relation.getLocalPart() + ") in " + user); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java index de55f4dc2c1..eb6e6496994 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java @@ -102,7 +102,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test001testImportBaseUsers() throws Exception { final String TEST_NAME = "test001testImportBaseUsers"; - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_IMPORT_BASE_USERS_FILE); @@ -230,7 +230,7 @@ public void test500chageTaskPolicyRule() throws Exception { @Test public void test520changeActivationThreeAccounts() throws Exception { final String TEST_NAME = "test520changeActivationThreeAccounts"; - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); //GIVEN openDJController.executeLdifChange(LDIF_CHANGE_ACTIVATION_FILE); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java index 05cbf895eb6..b6ba0613b75 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java @@ -87,7 +87,7 @@ public void test600chageTaskPolicyRule() throws Exception { @Test public void test610testFullRecon() throws Exception { final String TEST_NAME = "test610testFullRecon"; - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); //WHEN when(); @@ -107,7 +107,7 @@ public void test610testFullRecon() throws Exception { @Test public void test611testFullRecon() throws Exception { final String TEST_NAME = "test611testFullRecon"; - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); openDJController.delete("uid=user10,ou=People,dc=example,dc=com"); openDJController.delete("uid=user11,ou=People,dc=example,dc=com"); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java index 23cc864a102..9f3aecbf747 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java @@ -750,7 +750,7 @@ public void test152ModifySrcAccountHermanDeleteOrg() throws Exception { public void test200CreateUserAssignOrgPwdPolicy() throws Exception { final String TEST_NAME = "test200CreateUserAssignOrgPwdPolicy"; Task task = getTestTask(); - OperationResult result = createOperationalResult(); + OperationResult result = createOperationResult(); //prepare password policies addObject(GLOBAL_PASSWORD_POLICY_FILE); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java index 45bb548d52e..d64d7a0ce2b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java @@ -16,8 +16,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -56,8 +54,6 @@ public class TestNotoriousOrg extends AbstractNotoriousTest { public static final File ORG_NOTORIOUS_FILE = new File(TEST_DIR, "org-notorious.xml"); public static final String ORG_NOTORIOUS_OID = "f79fc21a-4d0a-11e7-ad8d-f7fe1a23c68a"; - private static final Trace LOGGER = TraceManager.getTrace(TestNotoriousOrg.class); - @Override protected String getNotoriousOid() { return ORG_NOTORIOUS_OID; @@ -93,7 +89,7 @@ protected void addNotoriousRole(OperationResult result) throws Exception { PrismObject org = parseObject(getNotoriousFile()); OrgType orgType = org.asObjectable(); fillNotorious(orgType); - LOGGER.info("Adding {}:\n{}", org, org.debugDump(1)); + logger.info("Adding {}:\n{}", org, org.debugDump(1)); repositoryService.addObject(org, null, result); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java index 6c1fc3e920b..40214f1624d 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java @@ -6,70 +6,40 @@ */ package com.evolveum.midpoint.testing.story.notorious; -import static org.testng.AssertJUnit.assertEquals; - import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - import javax.xml.namespace.QName; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; -import com.evolveum.midpoint.model.api.context.ModelContext; import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.internals.InternalInspector; -import com.evolveum.midpoint.schema.internals.InternalMonitor; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.util.MiscSchemaUtil; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.MidPointTestConstants; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * Testing bushy roles hierarchy. Especially reuse of the same role * in the rich role hierarchy. It looks like this: - * - * user - * | - * +------+------+-----+-----+-.... - * | | | | | - * v v v v v - * Ra1 Ra2 Ra3 Ra4 Ra5 - * | | | | | - * +------+------+-----+-----+ - * | - * v - * notorious role - * | - * +------+------+-----+-----+-.... - * | | | | | - * v v v v v - * Rb1 Rb2 Rb3 Rb4 Rb5 - * + *

+ * user + * | + * +------+------+-----+-----+-.... + * | | | | | + * v v v v v + * Ra1 Ra2 Ra3 Ra4 Ra5 + * | | | | | + * +------+------+-----+-----+ + * | + * v + * notorious role + * | + * +------+------+-----+-----+-.... + * | | | | | + * v v v v v + * Rb1 Rb2 Rb3 Rb4 Rb5 + *

* Naive mode of evaluation would imply cartesian product of all Rax and Rbx * combinations. That's painfully inefficient. Therefore make sure that the * notorious roles is evaluated only once and the results of the evaluation @@ -77,15 +47,13 @@ * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestNotoriousRole extends AbstractNotoriousTest { public static final File ROLE_NOTORIOUS_FILE = new File(TEST_DIR, "role-notorious.xml"); public static final String ROLE_NOTORIOUS_OID = "1e95a1b8-46d1-11e7-84c5-e36e43bb0f00"; - private static final Trace LOGGER = TraceManager.getTrace(TestNotoriousRole.class); - @Override protected String getNotoriousOid() { return ROLE_NOTORIOUS_OID; @@ -121,7 +89,7 @@ protected void addNotoriousRole(OperationResult result) throws Exception { PrismObject role = parseObject(getNotoriousFile()); RoleType roleType = role.asObjectable(); fillNotorious(roleType); - LOGGER.info("Adding {}:\n{}", role, role.debugDump(1)); + logger.info("Adding {}:\n{}", role, role.debugDump(1)); repositoryService.addObject(role, null, result); } diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AbstractUnitTest.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AbstractUnitTest.java index 1437c01a8a1..e41336b745d 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AbstractUnitTest.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AbstractUnitTest.java @@ -31,7 +31,7 @@ public void startTestContext(ITestResult testResult) { public void finishTestContext(ITestResult testResult) { SimpleMidpointTestContext context = SimpleMidpointTestContext.get(); SimpleMidpointTestContext.destroy(); - displayDefaultTestFooter(context.getTestName(), testResult); + displayTestFooter(context.getTestName(), testResult); } @Override diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java index 5eea88bff14..e3756b522db 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java @@ -24,6 +24,7 @@ public interface MidpointTestMixin { String TEST_OUT_SUFFIX = " ]======================================\n"; String TEST_OUT_FOOTER_PREFIX = "====== "; String TEST_OUT_FOOTER_SUFFIX = "\n"; + String TEST_OUT_SECTION_PREFIX = "\n\n----- "; String TEST_OUT_SECTION_SUFFIX = " --------------------------------------\n"; String TEST_LOG_SECTION_PREFIX = "----- "; @@ -90,17 +91,35 @@ default String getTestNameLong() { "Current test-method context MUST NOT be null"); } + /** + * Displays test header with the test name. + * Not intended for tests classes, used by lifecycle methods in our test superclasses. + */ default void displayTestTitle(String testTitle) { System.out.println(TEST_OUT_PREFIX + testTitle + TEST_OUT_SUFFIX); logger().info(TEST_LOG_PREFIX + testTitle + TEST_LOG_SUFFIX); } - default void displayDefaultTestFooter(String testTitle, ITestResult testResult) { + /** + * Displays test footer with the test name and test duration. + * Not intended for tests classes, used by lifecycle methods in our test superclasses. + */ + default void displayTestFooter(String testTitle, ITestResult testResult) { long testMsDuration = testResult.getEndMillis() - testResult.getStartMillis(); System.out.println(TEST_OUT_FOOTER_PREFIX + testTitle + " FINISHED in " + testMsDuration + " ms" + TEST_OUT_FOOTER_SUFFIX); logger().info(TEST_LOG_PREFIX + testTitle + " FINISHED in " + testMsDuration + " ms" + TEST_LOG_SUFFIX); } + default void display(String text) { + System.out.println("\n*** " + text); + logger().debug("*** {}", text); + } + + default void display(String title, String value) { + System.out.println("\n*** " + title + "\n" + value); + logger().debug("*** {}\n{}", title, value); + } + /** * Displays "given" subsection header with test name. * Even better, use {@link #given(String)} and provide human readable description. From f48a165343438fe5fdd15156a187b243f85d902d Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Wed, 4 Mar 2020 22:28:22 +0100 Subject: [PATCH 6/8] testing/story/pom.xml: forgotten skip property out (bad override) --- testing/story/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/testing/story/pom.xml b/testing/story/pom.xml index e3d2f618b6a..f9be578b7ac 100644 --- a/testing/story/pom.xml +++ b/testing/story/pom.xml @@ -19,11 +19,6 @@ midPoint Testing - Story Tests - - - true - - com.evolveum.midpoint.infra From 55af3894757bd6a9f361df7d359cbcc0ff4e2082 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Thu, 5 Mar 2020 00:33:33 +0100 Subject: [PATCH 7/8] TestIntegrationObjectWrapperFactory fix, sometimes null vararg is good --- .../TestIntegrationObjectWrapperFactory.java | 120 +++++++++--------- .../midpoint/web/WrapperTestUtil.java | 100 +++++++++------ 2 files changed, 119 insertions(+), 101 deletions(-) diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java index 7b5479c0778..7cf9595729c 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/gui/TestIntegrationObjectWrapperFactory.java @@ -208,6 +208,64 @@ private void assertContainersPaths(PrismObjectWrapper objectWrapper, Collecti assertEquals("wrong container paths in "+objectWrapper, expectedUniformPaths, realUniformPaths); } + @Test + public void test102CreateWrapperUserEmpty() throws Exception { + PrismObject user = getUser(USER_EMPTY_OID); + PrismObject userOld = user.clone(); + + // WHEN + when(); + + Task task = createTask(); + OperationResult result = task.getResult(); + + ModelServiceLocator modelServiceLocator = getServiceLocator(task); + PrismObjectWrapperFactory factory = modelServiceLocator.findObjectWrapperFactory(user.getDefinition()); + WrapperContext context = new WrapperContext(task, result); + + PrismObjectWrapper objectWrapper = factory.createObjectWrapper(user, ItemStatus.NOT_CHANGED, context); + + // THEN + then(); + + PrismTestUtil.display("Wrapper after", objectWrapper); + + WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, userOld, ItemStatus.NOT_CHANGED); + assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); + + WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), null, user, ItemStatus.NOT_CHANGED); + assertEquals("wrong number of containers in "+objectWrapper, 1, objectWrapper.getValues().size()); + PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); + WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_EMPTY_USERNAME)); + WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE, null); + + // Not sure about this +// ContainerWrapper activationContainerWrapper = objectWrapper.findContainer(ItemPath.create(UserType.F_ACTIVATION)); +// assertNull("Unexpected activation "+activationContainerWrapper, activationContainerWrapper); + + assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadOnly()); + + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_NAME, true); + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_GIVEN_NAME, true); // emphasized + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_FULL_NAME, true); // emphasized + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_ADDITIONAL_NAME, false); // empty + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_LOCALITY, false); // empty + + // WHEN + mainContainerValueWrapper.setShowEmpty(true); + + // THEN + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_NAME, true); + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_GIVEN_NAME, true); // emphasized + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_FULL_NAME, true); // emphasized + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_ADDITIONAL_NAME, true); // empty + assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_LOCALITY, true); // empty + + ObjectDelta objectDelta = objectWrapper.getObjectDelta(); + display("Delta", objectDelta); + assertTrue("non-empty delta produced from wrapper: "+objectDelta, objectDelta.isEmpty()); + } + /** * Create wrapper for brand new empty user. */ @@ -281,7 +339,7 @@ public void test112CreateWrapperUserNewman() throws Exception { PrismObject user = getUserDefinition().instantiate(); when(); - Task task = getTestTask(); + Task task = createTask(); OperationResult result = task.getResult(); ModelServiceLocator modelServiceLocator = getServiceLocator(task); @@ -309,7 +367,7 @@ public void test112CreateWrapperUserNewman() throws Exception { WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), null, user, ItemStatus.ADDED); assertEquals("wrong number of containers in "+objectWrapper, 1, objectWrapper.getValues().size()); WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_NEWMAN_USERNAME)); - WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE); + WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE, null); WrapperTestUtil.assertPropertyWrapper(mainContainerValueWrapper, extensionPath(PIRACY_SHIP), USER_NEWMAN_SHIP); PrismContainerWrapper activationContainerWrapper = objectWrapper.findContainer(UserType.F_ACTIVATION); @@ -350,64 +408,6 @@ public void test112CreateWrapperUserNewman() throws Exception { PrismAsserts.assertItems(objectToAdd, 5); } - @Test - public void test102CreateWrapperUserEmpty() throws Exception { - PrismObject user = getUser(USER_EMPTY_OID); - PrismObject userOld = user.clone(); - - // WHEN - when(); - - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ModelServiceLocator modelServiceLocator = getServiceLocator(task); - PrismObjectWrapperFactory factory = modelServiceLocator.findObjectWrapperFactory(user.getDefinition()); - WrapperContext context = new WrapperContext(task, result); - - PrismObjectWrapper objectWrapper = factory.createObjectWrapper(user, ItemStatus.NOT_CHANGED, context); - - // THEN - then(); - - PrismTestUtil.display("Wrapper after", objectWrapper); - - WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), "user description", user, userOld, ItemStatus.NOT_CHANGED); - assertContainersPaths(objectWrapper, BASIC_USER_CONTAINERS_PATHS); - - WrapperTestUtil.assertWrapper(objectWrapper, getString("prismContainer.mainPanelDisplayName"), null, user, ItemStatus.NOT_CHANGED); - assertEquals("wrong number of containers in "+objectWrapper, 1, objectWrapper.getValues().size()); - PrismContainerValueWrapper mainContainerValueWrapper = objectWrapper.getValue(); - WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_EMPTY_USERNAME)); - WrapperTestUtil.assertPropertyWrapperByName(mainContainerValueWrapper, UserType.F_TIMEZONE); - - // Not sure about this -// ContainerWrapper activationContainerWrapper = objectWrapper.findContainer(ItemPath.create(UserType.F_ACTIVATION)); -// assertNull("Unexpected activation "+activationContainerWrapper, activationContainerWrapper); - - assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadOnly()); - - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_NAME, true); - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_GIVEN_NAME, true); // emphasized - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_FULL_NAME, true); // emphasized - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_ADDITIONAL_NAME, false); // empty - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_LOCALITY, false); // empty - - // WHEN - mainContainerValueWrapper.setShowEmpty(true); - - // THEN - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_NAME, true); - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_GIVEN_NAME, true); // emphasized - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_FULL_NAME, true); // emphasized - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_ADDITIONAL_NAME, true); // empty - assertItemWrapperFullConrol(mainContainerValueWrapper, UserType.F_LOCALITY, true); // empty - - ObjectDelta objectDelta = objectWrapper.getObjectDelta(); - display("Delta", objectDelta); - assertTrue("non-empty delta produced from wrapper: "+objectDelta, objectDelta.isEmpty()); - } - @Test public void test150CreateWrapperShadow() throws Exception { diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java index 05bf0520ffa..29dfe18518f 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java @@ -6,6 +6,13 @@ */ package com.evolveum.midpoint.web; +import static org.testng.AssertJUnit.*; + +import java.util.Arrays; +import java.util.List; + +import org.testng.AssertJUnit; + import com.evolveum.midpoint.gui.api.prism.ItemStatus; import com.evolveum.midpoint.gui.api.prism.ItemWrapper; import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; @@ -22,26 +29,25 @@ import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import org.testng.AssertJUnit; - -import java.util.Arrays; -import java.util.List; - -import static org.testng.AssertJUnit.*; /** * @author semancik */ public class WrapperTestUtil { - public static void fillInPropertyWrapper(ModelServiceLocator modelServiceLocator, PrismContainerValueWrapper containerWrapper, ItemPath itemPath, T... newValues) throws SchemaException { + public static void fillInPropertyWrapper( + ModelServiceLocator modelServiceLocator, PrismContainerValueWrapper containerWrapper, + ItemPath itemPath, T... newValues) + throws SchemaException { PrismPropertyWrapper itemWrapper = containerWrapper.findProperty(itemPath); - assertNotNull("No item wrapper for path "+itemPath+" in "+containerWrapper, itemWrapper); + assertNotNull("No item wrapper for path " + itemPath + " in " + containerWrapper, itemWrapper); fillInPropertyWrapper(modelServiceLocator, itemWrapper, itemPath.lastName(), newValues); } - private static void fillInPropertyWrapper(ModelServiceLocator modelServiceLocator, PrismPropertyWrapper itemWrapper, ItemName itemName, T... newValues) throws SchemaException { - for (T newValue: newValues) { + private static void fillInPropertyWrapper(ModelServiceLocator modelServiceLocator, + PrismPropertyWrapper itemWrapper, ItemName itemName, T... newValues) + throws SchemaException { + for (T newValue : newValues) { List valueWrappers = itemWrapper.getValues(); PrismValueWrapper lastValueWrapper = valueWrappers.get(valueWrappers.size() - 1); PrismPropertyValue pval = (PrismPropertyValue) lastValueWrapper.getNewValue(); @@ -49,53 +55,60 @@ private static void fillInPropertyWrapper(ModelServi } } - public static void assertPropertyWrapper(PrismContainerValueWrapper containerWrapper, ItemPath itemPath, T... expectedValues) throws SchemaException { + public static void assertPropertyWrapper( + PrismContainerValueWrapper containerWrapper, ItemPath itemPath, T... expectedValues) + throws SchemaException { ItemWrapper itemWrapper = containerWrapper.findItem(itemPath, ItemWrapper.class); - assertNotNull("No item wrapper for path "+itemPath+" in "+containerWrapper, itemWrapper); + assertNotNull("No item wrapper for path " + itemPath + " in " + containerWrapper, itemWrapper); assertPropertyWrapper(containerWrapper, itemWrapper, itemPath.lastName(), expectedValues); } // todo better name - public static void assertPropertyWrapperByName(PrismContainerValueWrapper containerWrapper, ItemName itemName, T... expectedValues) throws SchemaException { + public static void assertPropertyWrapperByName( + PrismContainerValueWrapper containerWrapper, ItemName itemName, T... expectedValues) + throws SchemaException { ItemWrapper itemWrapper = containerWrapper.findItem(itemName, ItemWrapper.class); - assertNotNull("No item wrapper "+itemName+" in "+containerWrapper, itemWrapper); + assertNotNull("No item wrapper " + itemName + " in " + containerWrapper, itemWrapper); assertPropertyWrapper(containerWrapper, itemWrapper, itemName, expectedValues); } - private static void assertPropertyWrapper(PrismContainerValueWrapper containerWrapper, ItemWrapper itemWrapper, ItemName itemName, T... expectedValues) { + private static void assertPropertyWrapper( + PrismContainerValueWrapper containerWrapper, ItemWrapper itemWrapper, + ItemName itemName, T... expectedValues) { List valueWrappers = itemWrapper.getValues(); - assertPropertyWrapperValues("item wrapper "+itemName+" in "+containerWrapper, valueWrappers, expectedValues); + assertPropertyWrapperValues("item wrapper " + itemName + " in " + containerWrapper, valueWrappers, expectedValues); } - public static void assertPropertyWrapperValues(String desc, List valueWrappers, T... expectedValues) { + public static void assertPropertyWrapperValues( + String desc, List valueWrappers, T... expectedValues) { if (expectedValues == null) { expectedValues = (T[]) new Object[] { null }; } - assertEquals("Wrong number of values in "+desc+"; was: "+valueWrappers+", expected: "+Arrays.toString(expectedValues), expectedValues.length, valueWrappers.size()); + assertEquals("Wrong number of values in " + desc + "; was: " + valueWrappers + ", expected: " + Arrays.toString(expectedValues), expectedValues.length, valueWrappers.size()); if (expectedValues.length == 0) { return; } - for (PrismValueWrapper vw: valueWrappers) { + for (PrismValueWrapper vw : valueWrappers) { PrismValue actualPval = vw.getNewValue(); if (actualPval instanceof PrismPropertyValue) { - T actualValue = ((PrismPropertyValue)actualPval).getValue(); - if (expectedValues == null || expectedValues.length == 0 || ( expectedValues.length == 1 && expectedValues[0] == null)) { + T actualValue = ((PrismPropertyValue) actualPval).getValue(); + if (expectedValues == null || expectedValues.length == 0 || (expectedValues.length == 1 && expectedValues[0] == null)) { if (!isEmptyValue((PrismPropertyValue) vw.getOldValue())) { - AssertJUnit.fail("Unexpected value "+actualValue+" in value wrapper in "+desc+"; was: "+valueWrappers+", expected: "+ Arrays.toString(expectedValues)); + AssertJUnit.fail("Unexpected value " + actualValue + " in value wrapper in " + desc + "; was: " + valueWrappers + ", expected: " + Arrays.toString(expectedValues)); } } else { boolean found = false; - for (T expectedValue: expectedValues) { + for (T expectedValue : expectedValues) { if (MiscUtil.equals(expectedValue, actualValue)) { found = true; } } if (!found) { - AssertJUnit.fail("Unexpected value "+actualValue+" in value wrapper in "+desc+"; was: "+valueWrappers+", expected: "+Arrays.toString(expectedValues)); + AssertJUnit.fail("Unexpected value " + actualValue + " in value wrapper in " + desc + "; was: " + valueWrappers + ", expected: " + Arrays.toString(expectedValues)); } } } else { - AssertJUnit.fail("expected PrismPropertyValue in value wrapper in "+desc+", but got "+actualPval.getClass()); + AssertJUnit.fail("expected PrismPropertyValue in value wrapper in " + desc + ", but got " + actualPval.getClass()); } } @@ -106,48 +119,53 @@ private static boolean isEmptyValue(PrismPropertyValue pval) { if (val == null) { return true; } - if (val instanceof String && ((String)val).isEmpty()) { + if (val instanceof String && ((String) val).isEmpty()) { return true; } - if (val instanceof PolyString && ((PolyString)val).isEmpty()) { + if (val instanceof PolyString && ((PolyString) val).isEmpty()) { return true; } return false; } - public static void assertWrapper(PrismContainerWrapper containerWrapper, String displayName, - ItemPath expectedPath, PrismObject object, ItemStatus status) throws SchemaException { + public static void assertWrapper( + PrismContainerWrapper containerWrapper, String displayName, + ItemPath expectedPath, PrismObject object, ItemStatus status) + throws SchemaException { PrismContainer container; if (expectedPath == null) { container = (PrismContainer) object; } else { container = object.findContainer(expectedPath); } - assertWrapper(containerWrapper, displayName, expectedPath, container, expectedPath==null, status); + assertWrapper(containerWrapper, displayName, expectedPath, container, expectedPath == null, status); } - public static void assertWrapper(PrismContainerWrapper containerWrapper, String displayName, ItemPath expectedPath, - PrismContainer container, boolean isMain, ItemStatus status) throws SchemaException { + public static void assertWrapper( + PrismContainerWrapper containerWrapper, String displayName, ItemPath expectedPath, + PrismContainer container, boolean isMain, ItemStatus status) + throws SchemaException { assertNotNull("null wrapper", containerWrapper); PrismAsserts.assertEquivalent("Wrong path in wrapper " + containerWrapper, expectedPath == null ? ItemPath.EMPTY_PATH : expectedPath, containerWrapper.getPath()); if (container != null) { - assertEquals("Wrong item in wrapper "+containerWrapper, container, containerWrapper.getItem()); + assertEquals("Wrong item in wrapper " + containerWrapper, container, containerWrapper.getItem()); } - assertEquals("Wrong displayName in wrapper "+containerWrapper, displayName, containerWrapper.getValue().getDisplayName()); - assertEquals("Wrong status in wrapper "+containerWrapper, status, containerWrapper.getStatus()); + assertEquals("Wrong displayName in wrapper " + containerWrapper, displayName, containerWrapper.getValue().getDisplayName()); + assertEquals("Wrong status in wrapper " + containerWrapper, status, containerWrapper.getStatus()); } - public static void assertWrapper(PrismObjectWrapper objectWrapper, String displayName, String description, PrismObject object, PrismObject objectOld, - ItemStatus status) { + public static void assertWrapper( + PrismObjectWrapper objectWrapper, String displayName, String description, + PrismObject object, PrismObject objectOld, ItemStatus status) { assertNotNull("null wrapper", objectWrapper); - assertEquals("Wrong object in wrapper "+objectWrapper, object, objectWrapper.getObject()); + assertEquals("Wrong object in wrapper " + objectWrapper, object, objectWrapper.getObject()); if (ItemStatus.ADDED != objectWrapper.getStatus()) { assertEquals("Wrong old object in wrapper " + objectWrapper, objectOld, objectWrapper.getObjectOld()); } - assertFalse("object and old object not cloned in "+objectWrapper, objectWrapper.getObject() == objectWrapper.getObjectOld()); - assertEquals("Wrong displayName in wrapper "+objectWrapper, displayName, objectWrapper.getValue().getDisplayName()); - assertEquals("Wrong status in wrapper "+objectWrapper, status, objectWrapper.getStatus()); + assertFalse("object and old object not cloned in " + objectWrapper, objectWrapper.getObject() == objectWrapper.getObjectOld()); + assertEquals("Wrong displayName in wrapper " + objectWrapper, displayName, objectWrapper.getValue().getDisplayName()); + assertEquals("Wrong status in wrapper " + objectWrapper, status, objectWrapper.getStatus()); } } From 5d9b9a994b49dbac3b6235523c59a0d2ecc89ced Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Thu, 5 Mar 2020 08:50:09 +0100 Subject: [PATCH 8/8] POMs: one more fix to run testing/story in "extratest" profile Mismatch between and elements, now documented in comments. --- pom.xml | 3 ++- testing/pom.xml | 21 +++++++++++++++++++-- testing/story/pom.xml | 2 +- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 1269a50ba50..5cf468d864b 100644 --- a/pom.xml +++ b/pom.xml @@ -2042,7 +2042,8 @@ extratest diff --git a/testing/pom.xml b/testing/pom.xml index 66886777be2..c0af6b92451 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -25,11 +25,20 @@ sanity conntest longtest @@ -59,6 +68,14 @@ extratest + true diff --git a/testing/story/pom.xml b/testing/story/pom.xml index f9be578b7ac..01cfc22c7fc 100644 --- a/testing/story/pom.xml +++ b/testing/story/pom.xml @@ -306,7 +306,7 @@ maven-failsafe-plugin - ${skipStoryTests} + ${skipStoryTests} alphabetical