You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by va...@apache.org on 2023/01/20 07:10:32 UTC
[qpid-broker-j] branch main updated: QPID-8615: [Broker-J] JUnit 5 migration (#165)
This is an automated email from the ASF dual-hosted git repository.
vavrtom pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-broker-j.git
The following commit(s) were added to refs/heads/main by this push:
new 604522b29c QPID-8615: [Broker-J] JUnit 5 migration (#165)
604522b29c is described below
commit 604522b29c308a75c97d407fec648ba4ff12fbeb
Author: Daniil Kirilyuk <da...@gmail.com>
AuthorDate: Fri Jan 20 08:10:26 2023 +0100
QPID-8615: [Broker-J] JUnit 5 migration (#165)
---
.../berkeleydb/AMQShortStringEncodingTest.java | 15 +-
.../store/berkeleydb/BDBHAVirtualHostNodeTest.java | 250 ++--
.../BDBMessageStoreConfigurationTest.java | 13 +-
.../berkeleydb/BDBMessageStoreQuotaEventsTest.java | 14 +-
.../store/berkeleydb/BDBMessageStoreTest.java | 39 +-
.../store/berkeleydb/BDBPreferenceStoreTest.java | 86 +-
.../berkeleydb/BDBStoreUpgradeTestPreparer.java | 21 +-
.../store/berkeleydb/CoalescingCommitterTest.java | 31 +-
.../store/berkeleydb/EnvHomeRegistryTest.java | 11 +-
.../StandardEnvironmentFacadeFactoryTest.java | 37 +-
.../berkeleydb/StandardEnvironmentFacadeTest.java | 43 +-
.../ReplicatedEnvironmentFacadeTest.java | 535 ++++-----
.../tuple/ConfiguredObjectBindingTest.java | 15 +-
.../upgrade/AbstractUpgradeTestCase.java | 41 +-
.../berkeleydb/upgrade/DatabaseTemplateTest.java | 7 +-
.../berkeleydb/upgrade/MapJsonSerializerTest.java | 8 +-
.../berkeleydb/upgrade/UpgradeFrom4to5Test.java | 61 +-
.../berkeleydb/upgrade/UpgradeFrom5To6Test.java | 96 +-
.../berkeleydb/upgrade/UpgradeFrom7To8Test.java | 55 +-
.../berkeleydb/upgrade/UpgradeFrom8To9Test.java | 12 +-
.../upgrade/UpgraderFailOnNewerVersionTest.java | 19 +-
.../store/berkeleydb/upgrade/UpgraderTest.java | 32 +-
.../berkeleydb/BDBVirtualHostImplTest.java | 28 +-
.../berkeleydb/BDBHARemoteReplicationNodeTest.java | 46 +-
...BDBHAVirtualHostNodeOperationalLoggingTest.java | 72 +-
.../berkeleydb/BDBHAVirtualHostNodeTestHelper.java | 24 +-
.../berkeleydb/BDBVirtualHostNodeTest.java | 28 +-
.../store/berkeleydb/BDBAMQP10V0UpgradeTest.java | 27 +-
.../server/store/berkeleydb/BDBUpgradeTest.java | 156 ++-
.../server/store/berkeleydb/UpgradeTestBase.java | 6 +-
.../berkeleydb/replication/GroupJmsTestBase.java | 54 +-
.../berkeleydb/replication/MultiNodeTest.java | 89 +-
.../store/berkeleydb/replication/TwoNodeTest.java | 29 +-
broker-core/pom.xml | 60 -
.../org/apache/qpid/server/SelectorParserTest.java | 41 +-
.../org/apache/qpid/server/SystemLauncherTest.java | 101 +-
.../bytebuffer/QpidByteBufferOutputStreamTest.java | 49 +-
.../qpid/server/bytebuffer/QpidByteBufferTest.java | 652 +++++-----
.../startup/VirtualHostCreationTest.java | 65 +-
.../store/ManagementModeStoreHandlerTest.java | 361 +++---
.../StoreConfigurationChangeListenerTest.java | 28 +-
.../configuration/updater/TaskExecutorTest.java | 239 ++--
.../connection/ConnectionVersionValidatorTest.java | 69 +-
.../consumer/AbstractConsumerTargetTest.java | 126 +-
.../qpid/server/consumer/TestConsumerTarget.java | 21 +-
.../qpid/server/exchange/DirectExchangeTest.java | 474 +++-----
.../server/exchange/ExchangeStatisticsTest.java | 23 +-
.../qpid/server/exchange/FanoutExchangeTest.java | 405 +++----
.../qpid/server/exchange/HeadersBindingTest.java | 77 +-
.../qpid/server/exchange/HeadersExchangeTest.java | 319 +++--
.../apache/qpid/server/exchange/ProducerTest.java | 8 +-
.../qpid/server/exchange/TopicExchangeTest.java | 616 ++++------
.../exchange/topic/TopicExchangeResultTest.java | 40 +-
.../filter/ArrivalTimeFilterFactoryTest.java | 30 +-
.../qpid/server/filter/JMSSelectorFilterTest.java | 38 +-
.../qpid/server/logging/UnitTestMessageLogger.java | 10 +-
.../server/logging/UnitTestMessageLoggerTest.java | 43 +-
.../logging/actors/AMQPConnectionActorTest.java | 83 +-
.../server/logging/actors/BaseActorTestCase.java | 60 +-
.../actors/BaseConnectionActorTestCase.java | 35 +-
.../logging/actors/HttpManagementActorTest.java | 153 +--
.../logging/messages/AbstractTestMessages.java | 69 +-
.../logging/messages/BrokerMessagesTest.java | 77 +-
.../logging/messages/ChannelMessagesTest.java | 20 +-
.../logging/messages/ConnectionMessagesTest.java | 56 +-
.../logging/messages/ConsumerMessagesTest.java | 25 +-
.../logging/messages/ExchangeMessagesTest.java | 6 +-
.../messages/ManagementConsoleMessagesTest.java | 32 +-
.../logging/messages/MessageStoreMessagesTest.java | 20 +-
.../server/logging/messages/QueueMessagesTest.java | 4 +-
.../server/logging/messages/UserMessagesTest.java | 2 +-
.../logging/messages/VirtualHostMessagesTest.java | 3 +-
.../logging/subjects/AbstractTestLogSubject.java | 115 +-
.../logging/subjects/BindingLogSubjectTest.java | 41 +-
.../logging/subjects/ChannelLogSubjectTest.java | 15 +-
.../logging/subjects/ConnectionLogSubjectTest.java | 15 +-
.../logging/subjects/ExchangeLogSubjectTest.java | 26 +-
.../subjects/MessageStoreLogSubjectTest.java | 39 +-
.../logging/subjects/QueueLogSubjectTest.java | 30 +-
.../server/logging/subjects/TestBlankSubject.java | 1 -
.../server/message/AbstractServerMessageTest.java | 49 +-
.../internal/InternalMessageMutatorTest.java | 14 +-
.../server/model/AttributeValueConverterTest.java | 116 +-
.../apache/qpid/server/model/BrokerTestHelper.java | 208 ++--
.../model/ConfiguredObjectJacksonModuleTest.java | 19 +-
.../qpid/server/model/UUIDGeneratorTest.java | 94 +-
.../apache/qpid/server/model/VirtualHostTest.java | 522 +++-----
.../qpid/server/model/adapter/BrokerImplTest.java | 238 ++--
.../adapter/FileBasedGroupProviderImplTest.java | 230 ++--
.../qpid/server/model/adapter/PortFactoryTest.java | 253 ++--
.../qpid/server/model/port/AmqpPortImplTest.java | 270 ++---
.../qpid/server/model/port/HttpPortImplTest.java | 159 +--
.../model/preferences/GenericPrincipalTest.java | 189 +--
.../model/preferences/PreferenceFactoryTest.java | 43 +-
.../model/preferences/PreferenceTestHelper.java | 42 +-
.../model/preferences/UserPreferencesTest.java | 155 +--
.../hierarchy/AbstractConfiguredObjectTest.java | 722 +++++-------
.../hierarchy/AncestorAttributeResolverTest.java | 96 +-
.../ConfiguredObjectTypeRegistryTest.java | 142 +--
.../hierarchy/InjectedAttributeTest.java | 348 +++---
.../testmodels/hierarchy/TestAbstractCarImpl.java | 20 +-
.../hierarchy/TestAbstractEngineImpl.java | 4 +-
.../hierarchy/TestAbstractGaugeImpl.java | 1 +
.../hierarchy/TestAbstractInstrumentPanelImpl.java | 3 +-
.../hierarchy/TestAbstractSensorImpl.java | 1 +
.../server/model/testmodels/hierarchy/TestCar.java | 7 +-
.../hierarchy/TestDigitalInstrumentPanelImpl.java | 1 -
.../model/testmodels/hierarchy/TestElecEngine.java | 1 +
.../testmodels/hierarchy/TestElecEngineImpl.java | 7 +-
.../model/testmodels/hierarchy/TestEngine.java | 8 +-
.../model/testmodels/hierarchy/TestGauge.java | 1 +
.../testmodels/hierarchy/TestInstrumentPanel.java | 2 +-
.../model/testmodels/hierarchy/TestKitCar.java | 1 +
.../model/testmodels/hierarchy/TestKitCarImpl.java | 9 +-
.../model/testmodels/hierarchy/TestModel.java | 39 +-
.../testmodels/hierarchy/TestPetrolEngine.java | 1 +
.../testmodels/hierarchy/TestPetrolEngineImpl.java | 2 +-
.../testmodels/hierarchy/TestRechargeable.java | 1 -
.../model/testmodels/hierarchy/TestSensor.java | 2 +-
.../testmodels/hierarchy/TestStandardCar.java | 1 -
.../testmodels/hierarchy/TestStandardCarImpl.java | 16 +-
.../hierarchy/TestTemperatureGaugeImpl.java | 5 +-
.../hierarchy/TestTemperatureSensorImpl.java | 1 -
.../lifecycle/AbstractConfiguredObjectTest.java | 298 ++---
.../testmodels/lifecycle/TestConfiguredObject.java | 19 +-
.../singleton/AbstractConfiguredObjectTest.java | 930 ++++++---------
.../testmodels/singleton/PreferencesTest.java | 519 ++++----
.../model/testmodels/singleton/TestModel.java | 14 +-
.../testmodels/singleton/TestSingletonImpl.java | 16 +-
.../plugin/AMQPProtocolVersionWrapperTest.java | 66 +-
.../ProtocolEngineCreatorComparatorTest.java | 27 +-
...ritedAccessControlContextThreadFactoryTest.java | 53 +-
.../qpid/server/queue/AbstractQueueTestBase.java | 1109 ++++++++---------
.../queue/FlowToDiskOverflowPolicyHandlerTest.java | 114 +-
.../qpid/server/queue/LastValueQueueListTest.java | 165 ++-
.../qpid/server/queue/LastValueQueueTest.java | 26 +-
.../qpid/server/queue/MockMessageInstance.java | 9 +-
.../qpid/server/queue/NotificationCheckTest.java | 23 +-
.../qpid/server/queue/PriorityQueueListTest.java | 138 +--
.../qpid/server/queue/PriorityQueueTest.java | 49 +-
...oducerFlowControlOverflowPolicyHandlerTest.java | 83 +-
.../qpid/server/queue/QueueEntryImplTestBase.java | 240 ++--
.../qpid/server/queue/QueueEntryListTestBase.java | 101 +-
.../server/queue/QueueMessageRecoveryTest.java | 84 +-
.../qpid/server/queue/QueueStatisticsTest.java | 16 +-
.../qpid/server/queue/RejectPolicyHandlerTest.java | 72 +-
.../queue/RingOverflowPolicyHandlerTest.java | 34 +-
.../qpid/server/queue/RingOverflowPolicyTest.java | 38 +-
.../queue/SelfValidatingSortedQueueEntryList.java | 47 +-
.../server/queue/SimpleQueueEntryImplTest.java | 48 +-
.../server/queue/SortedQueueEntryListTest.java | 180 ++-
.../qpid/server/queue/SortedQueueEntryTest.java | 63 +-
.../apache/qpid/server/queue/SortedQueueTest.java | 12 +-
.../server/queue/StandardQueueEntryListTest.java | 160 ++-
.../qpid/server/queue/StandardQueueTest.java | 123 +-
.../qpid/server/security/FileKeyStoreTest.java | 286 ++---
.../qpid/server/security/FileTrustStoreTest.java | 449 +++----
.../qpid/server/security/KeyStoreTestHelper.java | 32 +-
.../qpid/server/security/NonJavaKeyStoreTest.java | 112 +-
.../server/security/NonJavaTrustStoreTest.java | 183 ++-
.../security/SiteSpecificTrustStoreTest.java | 208 ++--
.../qpid/server/security/SubjectCreatorTest.java | 58 +-
.../security/TrustStoreMessageSourceTest.java | 45 +-
.../security/auth/AuthenticatedPrincipalTest.java | 107 +-
.../auth/AuthenticatedPrincipalTestHelper.java | 27 +-
.../security/auth/AuthenticationResultTest.java | 71 +-
.../server/security/auth/TestPrincipalUtils.java | 9 +-
.../security/auth/UsernamePrincipalTest.java | 31 +-
.../AbstractPasswordFilePrincipalDatabaseTest.java | 135 +--
...Base64MD5PasswordFilePrincipalDatabaseTest.java | 272 ++---
.../security/auth/database/HashedUserTest.java | 36 +-
.../PlainPasswordFilePrincipalDatabaseTest.java | 236 ++--
.../security/auth/database/PlainUserTest.java | 29 +-
.../AnonymousAuthenticationManagerTest.java | 53 +-
.../manager/AuthenticationResultCacherTest.java | 92 +-
...eUsernamePasswordAuthenticationManagerTest.java | 589 ++++------
.../manager/ExternalAuthenticationManagerTest.java | 155 ++-
.../manager/KerberosAuthenticationManagerTest.java | 120 +-
.../auth/manager/MD5AuthenticationManagerTest.java | 2 -
.../ManagedAuthenticationManagerTestBase.java | 225 ++--
...nPasswordDatabaseAuthenticationManagerTest.java | 121 +-
...sswordFileAuthenticationManagerFactoryTest.java | 66 +-
...PrincipalDatabaseAuthenticationManagerTest.java | 177 ++-
.../ScramSHA1AuthenticationManagerTest.java | 19 +-
.../manager/SimpleAuthenticationManagerTest.java | 115 +-
...SimpleLDAPAuthenticationManagerFactoryTest.java | 65 +-
.../SimpleLDAPAuthenticationManagerTest.java | 192 ++-
.../auth/manager/TestLdapDirectoryContext.java | 6 +-
.../ldap/SimpleLDAPAuthenticationManagerTest.java | 31 +-
.../OAuth2AuthenticationProviderImplTest.java | 144 +--
.../auth/manager/oauth2/OAuth2MockEndpoint.java | 53 +-
.../manager/oauth2/OAuth2MockEndpointHolder.java | 26 +-
.../qpid/server/security/auth/sasl/SaslUtil.java | 73 +-
.../sasl/anonymous/AnonymousNegotiatorTest.java | 17 +-
.../auth/sasl/crammd5/CramMd5NegotiatorTest.java | 117 +-
.../auth/sasl/external/ExternalNegotiatorTest.java | 161 ++-
.../auth/sasl/oauth2/OAuth2NegotiatorTest.java | 69 +-
.../auth/sasl/plain/PlainNegotiatorTest.java | 74 +-
.../auth/sasl/scram/ScramNegotiatorTest.java | 200 ++--
.../AESGCMKeyFileEncrypterFactoryTest.java | 6 +-
.../encryption/AESGCMKeyFileEncrypterTest.java | 221 ++--
.../encryption/AESKeyFileEncrypterFactoryTest.java | 9 +-
.../encryption/AESKeyFileEncrypterTest.java | 160 +--
.../AbstractAESKeyFileEncrypterFactoryTest.java | 142 +--
.../FileGroupDatabaseCaseInsensitiveTest.java | 102 +-
.../security/group/FileGroupDatabaseTest.java | 116 +-
.../server/security/group/GroupPrincipalTest.java | 56 +-
.../server/security/group/GroupProviderUtil.java | 18 +-
.../security/limit/ConnectionLimiterTest.java | 111 +-
.../server/session/AbstractAMQPSessionTest.java | 38 +-
.../apache/qpid/server/ssl/TrustManagerTest.java | 211 ++--
.../stats/FormattingStatisticsResolverTest.java | 82 +-
...ConfigurationStoreUpgraderAndRecovererTest.java | 59 +-
.../AbstractDurableConfigurationStoreTestCase.java | 181 ++-
.../qpid/server/store/BrokerRecovererTest.java | 215 ++--
.../store/BrokerStoreUpgraderAndRecovererTest.java | 1190 +++++++++----------
.../apache/qpid/server/store/EventManagerTest.java | 11 +-
.../JsonFileConfigStoreConfigurationTest.java | 18 +-
.../qpid/server/store/JsonFileConfigStoreTest.java | 293 ++---
.../qpid/server/store/MemoryMessageStoreTest.java | 9 +-
.../apache/qpid/server/store/MessageCounter.java | 4 +-
.../store/MessageStoreQuotaEventsTestBase.java | 66 +-
.../qpid/server/store/MessageStoreTestCase.java | 301 +++--
.../qpid/server/store/TestMemoryMessageStore.java | 18 +-
.../qpid/server/store/TestMessageMetaData.java | 18 +-
.../server/store/TestMessageMetaDataFactory.java | 8 +-
.../qpid/server/store/TestMessageMetaDataType.java | 35 +-
.../org/apache/qpid/server/store/TestRecord.java | 10 +-
.../qpid/server/store/UpgraderHelperTest.java | 12 +-
.../VirtualHostStoreUpgraderAndRecovererTest.java | 430 +++----
.../preferences/JsonFilePreferenceStoreTest.java | 136 +--
.../preferences/PreferencesRecovererTest.java | 68 +-
.../server/streams/CompositeInputStreamTest.java | 118 +-
.../apache/qpid/server/test/KerberosUtilities.java | 41 +-
.../org/apache/qpid/server/transport/SNITest.java | 228 ++--
.../server/transport/TCPandSSLTransportTest.java | 209 +---
.../transport/TransactionTimeoutTickerTest.java | 118 +-
.../network/security/ssl/SSLUtilTest.java | 259 ++--
.../server/txn/AsyncAutoCommitTransactionTest.java | 36 +-
.../qpid/server/txn/AutoCommitTransactionTest.java | 284 ++---
.../txn/FlowToDiskTransactionObserverTest.java | 55 +-
.../qpid/server/txn/LocalTransactionTest.java | 481 ++++----
.../org/apache/qpid/server/txn/MockAction.java | 2 +-
.../apache/qpid/server/txn/MockServerMessage.java | 18 +-
.../qpid/server/txn/MockStoreTransaction.java | 25 +-
.../server/util/ByteBufferInputStreamTest.java | 59 +-
.../qpid/server/util/CachingUUIDFactoryTest.java | 22 +-
.../qpid/server/util/CommandLineParserTest.java | 474 +++-----
.../apache/qpid/server/util/FileHelperTest.java | 110 +-
.../org/apache/qpid/server/util/FileUtilsTest.java | 425 +++----
.../org/apache/qpid/server/util/GZIPUtilsTest.java | 57 +-
.../apache/qpid/server/util/LoggerTestHelper.java | 26 +-
.../org/apache/qpid/server/util/SerialTest.java | 19 +-
.../apache/qpid/server/util/StringUtilTest.java | 36 +-
.../org/apache/qpid/server/util/StringsTest.java | 108 +-
.../virtualhost/AbstractVirtualHostTest.java | 137 +--
.../AsynchronousMessageStoreRecovererTest.java | 93 +-
.../qpid/server/virtualhost/CacheFactoryTest.java | 14 +-
.../virtualhost/FlowToDiskCheckingTaskTest.java | 46 +-
.../server/virtualhost/HouseKeepingTaskTest.java | 7 +-
.../SynchronousMessageStoreRecovererTest.java | 142 +--
.../server/virtualhost/TestMemoryVirtualHost.java | 2 -
.../VirtualHostInitialConfigurationTest.java | 79 +-
.../virtualhost/VirtualHostPropertiesNodeTest.java | 17 +-
.../virtualhost/VirtualHostQueueCreationTest.java | 147 +--
.../virtualhostalias/VirtualHostAliasTest.java | 104 +-
.../AbstractStandardVirtualHostNodeTest.java | 450 +++----
.../RedirectingVirtualHostNodeTest.java | 102 +-
.../virtualhostnode/TestVirtualHostNode.java | 17 +-
.../TestVirtualHostNodeFactory.java | 5 +-
.../security/access/config/AclFileParserTest.java | 129 +-
.../access/config/AclRulePredicatesTest.java | 59 +-
.../config/LegacyAccessControlAdapterTest.java | 20 +-
.../access/config/LegacyOperationTest.java | 7 +-
.../access/config/ObjectPropertiesTest.java | 19 +-
.../security/access/config/ObjectTypeTest.java | 9 +-
.../security/access/config/PropertyTest.java | 14 +-
.../access/config/RuleBasedAccessControlTest.java | 28 +-
.../security/access/config/RuleCollectorTest.java | 15 +-
.../server/security/access/config/RuleSetTest.java | 252 ++--
.../server/security/access/config/RuleTest.java | 180 ++-
.../predicates/RulePredicateBuilderTest.java | 10 +-
.../config/predicates/RulePredicateTest.java | 10 +-
.../security/access/firewall/FirewallRuleTest.java | 10 +-
.../access/firewall/HostnameFirewallRuleTest.java | 31 +-
.../access/firewall/NetworkFirewallRuleTest.java | 25 +-
.../AclFileAccessControlProviderFactoryTest.java | 23 +-
.../AclFileAccessControlProviderImplTest.java | 16 +-
.../RuleBasedAccessControlProviderImplTest.java | 7 +-
.../security/access/plugins/RuleOutcomeTest.java | 14 +-
.../security/access/util/PrefixTreeTest.java | 20 +-
.../MessageConverter_0_10_to_InternalTest.java | 92 +-
.../MessageConverter_Internal_to_0_10Test.java | 21 +-
.../v0_10/MessageTransferMessageMutatorTest.java | 10 +-
.../PropertyConverter_0_10_to_InternalTest.java | 96 +-
.../PropertyConverter_Internal_to_v0_10Test.java | 161 ++-
.../v0_10/ServerConnectionDelegateTest.java | 16 +-
.../protocol/v0_10/ServerSessionDelegateTest.java | 6 +-
.../server/protocol/v0_10/ServerSessionTest.java | 43 +-
.../protocol/v0_10/WindowCreditManagerTest.java | 58 +-
.../protocol/v0_10/transport/BBDecoderTest.java | 5 +-
.../protocol/v0_10/transport/BBEncoderTest.java | 53 +-
.../server/protocol/v0_10/transport/GenTest.java | 15 +-
.../protocol/v0_10/transport/RangeSetTest.java | 78 +-
.../org/apache/qpid/server/QpidExceptionTest.java | 24 +-
.../qpid/server/protocol/v0_8/AMQChannelTest.java | 56 +-
.../qpid/server/protocol/v0_8/AMQDecoderTest.java | 67 +-
.../protocol/v0_8/AMQMessageMutatorTest.java | 10 +-
.../protocol/v0_8/AMQPConnection_0_8Test.java | 58 +-
.../server/protocol/v0_8/AMQShortStringTest.java | 47 +-
.../qpid/server/protocol/v0_8/AMQTypeTest.java | 6 +-
.../server/protocol/v0_8/EncodingUtilsTest.java | 28 +-
.../qpid/server/protocol/v0_8/FieldTableTest.java | 31 +-
.../v0_8/MessageConverter_0_8_to_InternalTest.java | 89 +-
.../v0_8/MessageConverter_Internal_to_0_8Test.java | 21 +-
.../protocol/v0_8/MessageMetaDataFactoryTest.java | 31 +-
.../protocol/v0_8/Pre0_10CreditManagerTest.java | 91 +-
.../PropertyConverter_Internal_to_v0_8Test.java | 130 +-
.../PropertyConverter_v0_8_to_InternalTest.java | 65 +-
.../protocol/v0_8/ReferenceCountingTest.java | 26 +-
.../v0_8/UnacknowledgedMessageMapTest.java | 32 +-
.../BasicContentHeaderPropertiesTest.java | 24 +-
.../v0_8/transport/MessagePublishInfoImplTest.java | 24 +-
.../protocol/v1_0/store/bdb/BDBLinkStoreTest.java | 20 +-
.../v1_0/store/jdbc/JDBCLinkStoreTest.java | 1 -
.../protocol/v1_0/AMQPConnection_1_0ImplTest.java | 10 +-
.../protocol/v1_0/ConsumerTarget_1_0Test.java | 16 +-
.../server/protocol/v1_0/LinkRegistryTest.java | 90 +-
.../v1_0/MessageConverter_Internal_to_1_0Test.java | 39 +-
.../MessageConverter_v1_0_to_InternalTest.java | 276 +++--
.../protocol/v1_0/Message_1_0_MutatorTest.java | 18 +-
.../PropertyConverter_Internal_to_v1_0Test.java | 68 +-
.../PropertyConverter_v1_0_to_InternalTest.java | 83 +-
.../protocol/v1_0/ProtocolEngine_1_0_0Test.java | 50 +-
.../protocol/v1_0/SendingLinkEndpointTest.java | 7 +-
.../qpid/server/protocol/v1_0/Session_1_0Test.java | 237 ++--
.../v1_0/codec/StringTypeConstructorTest.java | 8 +-
.../protocol/v1_0/codec/ValueHandlerTest.java | 16 +-
.../v1_0/delivery/DeliveryRegistryImplTest.java | 9 +-
.../v1_0/delivery/UnsettledDeliveryTest.java | 7 +-
.../protocol/v1_0/framing/FrameHandlerTest.java | 20 +-
.../protocol/v1_0/store/LinkStoreTestCase.java | 60 +-
.../SoleConnectionDetectionPolicyTest.java | 16 +-
.../SoleConnectionEnforcementPolicyTest.java | 13 +-
.../StrongConnectionEstablishmentLimiterTest.java | 29 +-
.../MessageConverter_0_10_to_1_0Test.java | 37 +-
.../MessageConverter_1_0_to_v0_10Test.java | 346 +++---
.../PropertyConverter_0_10_to_1_0Test.java | 112 +-
.../PropertyConverter_1_0_to_0_10Test.java | 179 ++-
.../PropertyConverter_0_10_to_0_8Test.java | 93 +-
.../PropertyConverter_0_8_to_0_10Test.java | 101 +-
.../v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java | 35 +-
.../MessageConverter_1_0_to_v0_8Test.java | 384 +++---
.../PropertyConverter_0_8_to_1_0Test.java | 98 +-
.../PropertyConverter_1_0_to_0_8Test.java | 164 ++-
.../limits/config/ConnectionCountLimitTest.java | 14 +-
.../limits/config/ConnectionLimitsTest.java | 14 +-
.../connection/limits/config/FileParserTest.java | 18 +-
.../limits/config/RulePredicatesTest.java | 24 +-
.../limits/config/RuleSetCreatorTest.java | 16 +-
.../user/connection/limits/config/RuleSetTest.java | 19 +-
.../user/connection/limits/config/RuleTest.java | 20 +-
.../limits/outcome/AcceptRegistrationTest.java | 13 +-
.../limits/outcome/RejectRegistrationTest.java | 25 +-
broker-plugins/derby-store/pom.xml | 1 +
.../derby/DerbyMessageStoreConfigurationTest.java | 16 +-
.../derby/DerbyMessageStoreQuotaEventsTest.java | 15 +-
.../server/store/derby/DerbyMessageStoreTest.java | 29 +-
.../store/derby/DerbyPreferenceStoreTest.java | 56 +-
.../derby/DerbyVirtualHostNodeTest.java | 41 +-
.../qpid/server/logging/CallerDataFilterTest.java | 21 +-
.../logging/logback/event/LoggingEventTest.java | 16 +-
.../logback/graylog/GraylogAppenderTest.java | 17 +-
.../logging/logback/validator/AtLeastOneTest.java | 19 +-
.../logging/logback/validator/AtLeastTest.java | 17 +-
.../logging/logback/validator/AtLeastZeroTest.java | 19 +-
.../validator/GelfConfigurationValidatorTest.java | 57 +-
.../validator/GelfMessageStaticFieldsTest.java | 28 +-
.../server/logging/logback/validator/PortTest.java | 17 +-
.../logback/validator/TestConfiguredObject.java | 1 +
.../validator/TestConfiguredObjectFactory.java | 1 +
.../validator/TestConfiguredObjectTypeFactory.java | 1 +
.../apache/qpid/server/util/ArrayUtilsTest.java | 11 +-
.../logback/jdbc/InMemoryDatabaseTestBase.java | 8 +-
.../logback/jdbc/JDBCBrokerLoggerImplTest.java | 23 +-
.../logging/logback/jdbc/JDBCLoggerHelperTest.java | 15 +-
.../jdbc/JDBCSettingsDBNameResolverTest.java | 14 +-
.../JDBCSettingsDrivenConnectionSourceTest.java | 13 +-
.../jdbc/JDBCVirtualHostLoggerImplTest.java | 19 +-
.../BoneCPConnectionProviderFactoryTest.java | 14 +-
.../jdbc/bonecp/BoneCPConnectionProviderTest.java | 26 +-
.../jdbc/GenericJDBCConfigurationStoreTest.java | 12 +-
.../qpid/server/store/jdbc/JDBCDetailsTest.java | 8 +-
.../server/store/jdbc/JDBCMessageStoreTest.java | 33 +-
.../server/store/jdbc/JDBCSystemConfigTest.java | 12 +-
.../qpid/server/store/jdbc/TestJdbcUtils.java | 24 +-
.../virtualhost/jdbc/JDBCVirtualHostTest.java | 25 +-
.../jdbc/JDBCVirtualHostNodeTest.java | 23 +-
.../server/logging/logback/AppenderUtilsTest.java | 134 +--
.../logging/logback/BrokerFileLoggerTest.java | 59 +-
.../logback/BrokerLoggerStatusListenerTest.java | 23 +-
.../server/logging/logback/BrokerLoggerTest.java | 153 ++-
.../logging/logback/BrokerMemoryLoggerTest.java | 105 +-
.../BrokerNameAndLevelLogInclusionRuleTest.java | 90 +-
.../logging/logback/CompositeFilterTest.java | 65 +-
.../logback/ConnectionAndUserPredicateTest.java | 122 +-
.../Logback1027WorkaroundTurboFilterTest.java | 63 +-
.../logback/LoggerNameAndLevelFilterTest.java | 122 +-
.../logback/PrincipalLogEventFilterTest.java | 25 +-
.../logging/logback/QpidLoggerTurboFilterTest.java | 49 +-
.../logback/RollingPolicyDecoratorTest.java | 83 +-
.../logging/logback/RolloverWatcherTest.java | 232 ++--
.../logging/logback/StartupAppenderTest.java | 66 +-
.../VirtualHostLogEventExcludingFilterTest.java | 96 +-
.../logging/logback/VirtualHostLoggerTest.java | 144 ++-
...alHostNameAndLevelLogInclusionRuleImplTest.java | 108 +-
.../management/plugin/GunzipOutputStreamTest.java | 16 +-
.../management/plugin/HttpManagementTest.java | 60 +-
.../management/plugin/HttpManagementUtilTest.java | 9 +-
.../auth/OAuth2InteractiveAuthenticatorTest.java | 132 +--
.../auth/OAuth2PreemptiveAuthenticatorTest.java | 45 +-
...stractLegacyConfiguredObjectControllerTest.java | 7 +-
.../controller/GenericCategoryControllerTest.java | 6 +-
.../GenericLegacyConfiguredObjectTest.java | 6 +-
.../LatestManagementControllerAdapterTest.java | 6 +-
.../latest/LatestManagementControllerTest.java | 8 +-
.../v6_1/LegacyManagementControllerTest.java | 12 +-
.../v6_1/category/BindingControllerTest.java | 8 +-
.../v6_1/category/BrokerControllerTest.java | 6 +-
.../v6_1/category/ConsumerControllerTest.java | 13 +-
.../v6_1/category/DestinationControllerTest.java | 6 +-
.../v6_1/category/ExchangeControllerTest.java | 6 +-
.../LegacyCategoryControllerFactoryTest.java | 6 +-
.../category/LegacyCategoryControllerTest.java | 7 +-
.../v6_1/category/PortControllerTest.java | 6 +-
.../v6_1/category/QueueControllerTest.java | 6 +-
.../v6_1/category/SessionControllerTest.java | 6 +-
.../v6_1/category/VirtualHostControllerTest.java | 6 +-
.../v7_0/LegacyManagementControllerTest.java | 6 +-
.../v7_0/category/ContainerControllerTest.java | 7 +-
.../LegacyCategoryControllerFactoryTest.java | 7 +-
.../LegacyCategoryController_v8_0Test.java | 8 +-
.../management/plugin/csv/CSVFormatTest.java | 31 +-
.../management/plugin/filter/MethodFilterTest.java | 6 +-
.../management/plugin/report/ReportRunnerTest.java | 61 +-
.../management/plugin/report/TestBinaryReport.java | 2 -
.../servlet/query/ConfiguredObjectQueryTest.java | 123 +-
.../rest/ConfiguredObjectToMapConverterTest.java | 140 +--
.../plugin/servlet/rest/RequestInfoParserTest.java | 68 +-
.../rest/RestUserPreferenceHandlerTest.java | 1241 ++++++++------------
.../plugin/session/LoginLogoutReporterTest.java | 7 +-
.../prometheus/PrometheusContentFactoryTest.java | 6 +-
.../qpid/server/prometheus/QpidCollectorTest.java | 11 +-
.../query/engine/broker/BindingQueryTest.java | 4 +-
.../query/engine/broker/BrokerDigestQueryTest.java | 4 +-
.../query/engine/broker/CertificateQueryTest.java | 4 +-
.../query/engine/broker/ConnectionQueryTest.java | 4 +-
.../query/engine/broker/ConsumerQueryTest.java | 4 +-
.../query/engine/broker/DomainQueryTest.java | 4 +-
.../server/query/engine/broker/PortQueryTest.java | 4 +-
.../server/query/engine/broker/QueueQueryTest.java | 4 +-
.../query/engine/broker/SessionQueryTest.java | 4 +-
.../engine/broker/VirtualHostNodeQueryTest.java | 4 +-
.../query/engine/broker/VirtualHostQueryTest.java | 4 +-
.../query/engine/evaluator/QueryEvaluatorTest.java | 6 +-
.../parsing/converter/DateTimeConverterTest.java | 10 +-
.../expression/accessor/ChainedAccessorTest.java | 4 +-
.../arithmetic/ArithmeticExpressionsTest.java | 8 +-
.../arithmetic/NumericTypeConversionsTest.java | 6 +-
.../comparison/BetweenExpressionTest.java | 6 +-
.../expression/comparison/EqualExpressionTest.java | 6 +-
.../comparison/GreaterThanExpressionTest.java | 6 +-
.../GreaterThanOrEqualExpressionTest.java | 6 +-
.../expression/comparison/InExpressionTest.java | 4 +-
.../comparison/IsNullExpressionTest.java | 4 +-
.../comparison/LessThanExpressionTest.java | 6 +-
.../comparison/LessThanOrEqualExpressionTest.java | 6 +-
.../expression/comparison/LikeExpressionTest.java | 4 +-
.../expression/conditional/CaseExpressionTest.java | 4 +-
.../function/aggregation/AvgExpressionTest.java | 6 +-
.../function/aggregation/CountExpressionTest.java | 6 +-
.../function/aggregation/GroupByTest.java | 6 +-
.../function/aggregation/MaxExpressionTest.java | 6 +-
.../function/aggregation/MinExpressionTest.java | 6 +-
.../function/aggregation/SumExpressionTest.java | 6 +-
.../datetime/CurrentTimestampExpressionTest.java | 4 +-
.../function/datetime/DateAddExpressionTest.java | 6 +-
.../function/datetime/DateDiffExpressionTest.java | 6 +-
.../function/datetime/DateExpressionTest.java | 4 +-
.../function/datetime/ExtractExpressionTest.java | 6 +-
.../function/nulls/CoalesceExpressionTest.java | 8 +-
.../function/numeric/AbsExpressionTest.java | 6 +-
.../function/numeric/RoundExpressionTest.java | 6 +-
.../function/numeric/TruncExpressionTest.java | 6 +-
.../function/string/ConcatExpressionTest.java | 6 +-
.../function/string/LeftTrimExpressionTest.java | 8 +-
.../function/string/LengthExpressionTest.java | 6 +-
.../function/string/LowerExpressionTest.java | 8 +-
.../function/string/PositionExpressionTest.java | 6 +-
.../function/string/ReplaceExpressionTest.java | 8 +-
.../function/string/RightTrimExpressionTest.java | 8 +-
.../function/string/SubstringExpressionTest.java | 8 +-
.../function/string/TrimExpressionTest.java | 8 +-
.../function/string/UpperExpressionTest.java | 8 +-
.../expression/literal/LiteralExpressionTest.java | 6 +-
.../expression/logic/AndExpressionTest.java | 4 +-
.../expression/logic/NotExpressionTest.java | 4 +-
.../parsing/expression/logic/OrExpressionTest.java | 4 +-
.../expression/set/IntersectExpressionTest.java | 6 +-
.../expression/set/MinusExpressionTest.java | 6 +-
.../expression/set/UnionExpressionTest.java | 6 +-
.../factory/AccessorExpressionFactoryTest.java | 10 +-
.../factory/ArithmeticExpressionFactoryTest.java | 10 +-
.../parsing/factory/CollectorFactoryTest.java | 10 +-
.../factory/ComparisonExpressionFactoryTest.java | 10 +-
.../factory/ConditionalExpressionFactoryTest.java | 10 +-
.../factory/FunctionExpressionFactoryTest.java | 10 +-
.../factory/LiteralExpressionFactoryTest.java | 8 +-
.../factory/LogicExpressionFactoryTest.java | 10 +-
.../factory/NumberExpressionFactoryTest.java | 7 +-
.../factory/ProjectionExpressionFactoryTest.java | 10 +-
.../parsing/factory/SetExpressionFactoryTest.java | 8 +-
.../factory/UnaryExpressionFactoryTest.java | 10 +-
.../query/engine/parsing/query/AliasTest.java | 4 +-
.../query/engine/parsing/query/HavingTest.java | 6 +-
.../query/engine/parsing/query/OrderByTest.java | 6 +-
.../engine/parsing/query/QuerySettingsTest.java | 8 +-
.../engine/parsing/query/QueryValidatorTest.java | 6 +-
.../query/engine/parsing/query/SubqueryTest.java | 6 +-
.../query/engine/parsing/query/WithTest.java | 6 +-
.../FunctionParameterTypePredicateTest.java | 10 +-
.../FunctionParametersValidatorTest.java | 10 +-
.../validation/QueryExpressionValidatorTest.java | 10 +-
.../validation/SelectExpressionValidatorTest.java | 10 +-
.../test/java/org/apache/qpid/server/MainTest.java | 28 +-
.../apache/qpid/disttest/ArgumentParserTest.java | 45 +-
.../apache/qpid/disttest/ConfigFileHelperTest.java | 30 +-
.../java/org/apache/qpid/disttest/VisitorTest.java | 29 +-
.../disttest/client/ClientCommandVisitorTest.java | 32 +-
.../apache/qpid/disttest/client/ClientTest.java | 42 +-
.../disttest/client/ConsumerParticipantTest.java | 29 +-
.../qpid/disttest/client/MessageProviderTest.java | 42 +-
.../disttest/client/ParticipantExecutorTest.java | 7 +-
.../disttest/client/ParticipantRegistryTest.java | 35 +-
.../client/ParticipantResultFactoryTest.java | 42 +-
.../disttest/client/ParticipantTestHelper.java | 30 +-
.../disttest/client/ProducerParticipantTest.java | 31 +-
.../client/property/ListPropertyValueTest.java | 63 +-
.../client/property/PropertyValueFactoryTest.java | 38 +-
.../client/property/RandomPropertyValueTest.java | 45 +-
.../client/property/RangePropertyValueTest.java | 75 +-
.../client/property/SimplePropertyValueTest.java | 9 +-
.../disttest/controller/ClientRegistryTest.java | 34 +-
.../qpid/disttest/controller/ControllerTest.java | 35 +-
.../qpid/disttest/controller/HillClimberTest.java | 65 +-
.../controller/OrdinaryTestRunnerTest.java | 86 +-
.../controller/ParticipatingClientsTest.java | 40 +-
.../controller/config/ClientConfigTest.java | 33 +-
.../controller/config/ConfigReaderTest.java | 123 +-
.../disttest/controller/config/ConfigTest.java | 24 +-
.../controller/config/ConfigTestUtils.java | 12 +-
.../controller/config/ConnectionConfigTest.java | 25 +-
.../controller/config/ConsumerConfigTest.java | 22 +-
.../controller/config/IterationValueTest.java | 26 +-
.../config/JavaScriptConfigEvaluatorTest.java | 52 +-
.../config/MessageProviderConfigTest.java | 34 +-
.../controller/config/ProducerConfigTest.java | 40 +-
.../controller/config/SessionConfigTest.java | 27 +-
.../disttest/controller/config/TestConfigTest.java | 35 +-
.../controller/config/TestInstanceTest.java | 28 +-
.../qpid/disttest/db/ResultsDbWriterTest.java | 51 +-
.../qpid/disttest/jms/JmsMessageAdaptorTest.java | 20 +-
.../qpid/disttest/message/JsonHandlerTest.java | 64 +-
.../disttest/message/ParticipantResultTest.java | 24 +-
.../disttest/results/ResultsCsvWriterTest.java | 31 +-
.../qpid/disttest/results/ResultsTestFixture.java | 2 +-
.../disttest/results/ResultsXmlWriterTest.java | 15 +-
.../results/aggregation/AggregatorTest.java | 25 +-
.../ParticipantResultAggregatorTest.java | 78 +-
.../results/aggregation/SeriesStatisticsTest.java | 29 +-
.../aggregation/TestResultAggregatorTest.java | 87 +-
.../results/formatting/CSVFormatterTest.java | 22 +-
.../CSVOrderParticipantResultComparatorTest.java | 33 +-
.../chartbuilder/BaseChartBuilderTest.java | 28 +-
.../chartbuilder/ChartBuilderFactoryTest.java | 18 +-
.../charting/chartbuilder/ChartProductionTest.java | 50 +-
.../charting/chartbuilder/ColorFactoryTest.java | 20 +-
.../TimeSeriesBuilderCallbackTest.java | 24 +-
.../definition/ChartingDefinitionCreatorTest.java | 44 +-
.../definition/SeriesDefinitionCreatorTest.java | 50 +-
.../seriesbuilder/JdbcSeriesBuilderTest.java | 23 +-
.../seriesbuilder/JdbcUrlGeneratorTest.java | 19 +-
.../charting/seriesbuilder/SeriesRowTest.java | 19 +-
.../disttest/charting/writer/ChartWriterTest.java | 24 +-
pom.xml | 70 +-
.../systest/disttest/endtoend/EndToEndTest.java | 26 +-
qpid-systests-parent/pom.xml | 10 +-
qpid-test-utils/pom.xml | 51 +-
.../qpid/test/utils/CreateLdapServerExtension.java | 188 +++
.../qpid/test/utils/EmbeddedKdcExtension.java | 205 +++-
.../org/apache/qpid/test/utils/JvmVersion.java | 41 -
.../qpid/test/utils/QpidUnitTestExtension.java | 113 ++
.../apache/qpid/test/utils/QpidUnitTestRunner.java | 84 --
.../qpid/test/utils/SystemPropertySetter.java | 13 +-
.../org/apache/qpid/test/utils/TCPTunneler.java | 2 -
.../org/apache/qpid/test/utils/TestFileUtils.java | 43 +-
.../java/org/apache/qpid/test/utils/TestUtils.java | 29 +-
.../org/apache/qpid/test/utils/UnitTestBase.java | 150 ++-
.../apache/qpid/test/utils/tls/TlsResource.java | 71 +-
qpid-test-utils/src/main/resources/logback.xml | 1 +
.../EndToEndConversionTestBase.java | 15 +-
.../SimpleConversionTest.java | 104 +-
.../qpid/tests/protocol/v0_10/ConnectionTest.java | 31 +-
.../qpid/tests/protocol/v0_10/ExchangeTest.java | 15 +-
.../v0_10/LargeApplicationHeadersTest.java | 6 +-
.../tests/protocol/v0_10/LargeMessageBodyTest.java | 7 +-
.../qpid/tests/protocol/v0_10/MessageTest.java | 6 +-
.../qpid/tests/protocol/v0_10/ProtocolTest.java | 14 +-
.../qpid/tests/protocol/v0_10/QueueTest.java | 6 +-
.../qpid/tests/protocol/v0_10/SessionTest.java | 2 +-
.../qpid/tests/protocol/v0_10/TransactionTest.java | 6 +-
.../authtimeout/AuthenticationTimeoutTest.java | 7 +-
.../v0_10/extensions/exchange/ExchangeTest.java | 2 +-
.../extensions/maxsize/MaximumMessageSizeTest.java | 6 +-
.../extensions/message/MalformedMessageTest.java | 6 +-
.../protocol/v0_10/extensions/queue/QueueTest.java | 2 +-
.../transactiontimeout/TransactionTimeoutTest.java | 6 +-
.../apache/qpid/tests/protocol/v0_8/BasicTest.java | 12 +-
.../qpid/tests/protocol/v0_8/ChannelTest.java | 2 +-
.../qpid/tests/protocol/v0_8/ConnectionTest.java | 10 +-
.../qpid/tests/protocol/v0_8/ExchangeTest.java | 11 +-
.../qpid/tests/protocol/v0_8/LargeHeadersTest.java | 6 +-
.../qpid/tests/protocol/v0_8/LargeMessageTest.java | 7 +-
.../qpid/tests/protocol/v0_8/ProtocolTest.java | 14 +-
.../apache/qpid/tests/protocol/v0_8/QueueTest.java | 12 +-
.../qpid/tests/protocol/v0_8/TransactionTest.java | 6 +-
.../authtimeout/AuthenticationTimeoutTest.java | 7 +-
.../v0_8/extension/basic/MalformedMessageTest.java | 12 +-
.../basic/MalformedMessageValidation.java | 6 +-
.../extension/confirms/PublisherConfirmsTest.java | 6 +-
.../ExchangeDeclareInvalidOptionBehaviourTest.java | 10 +-
.../v0_8/extension/exchange/ExchangeTest.java | 2 +-
.../extension/maxsize/MaximumMessageSizeTest.java | 6 +-
.../protocoltimeout/ProtocolHeaderTimeoutTest.java | 2 +-
.../QueueDeclareInvalidOptionBehaviourTest.java | 2 +-
.../protocol/v0_8/extension/queue/QueueTest.java | 2 +-
.../transactiontimeout/TransactionTimeoutTest.java | 6 +-
.../v0_8/extension/tx/AsyncTransactionTest.java | 6 +-
.../qpid/tests/protocol/v1_0/DecodeErrorTest.java | 8 +-
.../protocol/v1_0/ExistingQueueAdminTest.java | 26 +-
.../qpid/tests/protocol/v1_0/ProtocolAsserts.java | 8 +-
.../anonymousterminus/AnonymousTerminusTest.java | 14 +-
.../bindmapjms/TemporaryDestinationTest.java | 6 +-
.../bindmapjms/TopicDestinationTest.java | 2 +-
.../v1_0/extensions/filter/FilterTest.java | 11 +-
.../v1_0/extensions/management/ManagementTest.java | 6 +-
.../qpid/message/MalformedMessageTest.java | 3 +-
.../extensions/qpid/queue/QueueDeletionTest.java | 10 +-
.../transactiontimeout/TransactionTimeoutTest.java | 6 +-
.../soleconn/CloseExistingPolicyTest.java | 2 +-
.../v1_0/extensions/soleconn/MixedPolicyTest.java | 2 +-
.../soleconn/RefuseConnectionPolicyTest.java | 2 +-
.../extensions/soleconn/SoleConnectionAsserts.java | 31 +-
.../v1_0/extensions/websocket/WebSocketTest.java | 28 +-
.../protocol/v1_0/messaging/DeleteOnCloseTest.java | 8 +-
.../protocol/v1_0/messaging/MessageFormatTest.java | 6 +-
.../protocol/v1_0/messaging/MultiTransferTest.java | 6 +-
.../tests/protocol/v1_0/messaging/OutcomeTest.java | 12 +-
.../protocol/v1_0/messaging/TransferTest.java | 48 +-
.../protocol/v1_0/transaction/DischargeTest.java | 14 +-
.../transaction/TransactionalTransferTest.java | 26 +-
.../v1_0/transport/ProtocolHeaderTest.java | 15 +-
.../v1_0/transport/connection/IdleTimeoutTest.java | 3 +-
.../v1_0/transport/connection/OpenTest.java | 6 +-
.../protocol/v1_0/transport/link/AttachTest.java | 2 +-
.../protocol/v1_0/transport/link/FlowTest.java | 2 +-
.../v1_0/transport/link/LinkStealingTest.java | 6 +-
.../v1_0/transport/link/ResumeDeliveriesTest.java | 44 +-
.../v1_0/transport/security/sasl/SaslTest.java | 21 +-
.../qpid/SaslAuthenticationTimeoutTest.java | 12 +-
.../protocol/v1_0/transport/session/BeginTest.java | 8 +-
.../org/apache/qpid/tests/http/HttpTestBase.java | 18 +-
.../org/apache/qpid/tests/http/HttpTestHelper.java | 15 +-
.../PreemptiveAuthenticationTest.java | 15 +-
.../qpid/tests/http/authentication/SaslTest.java | 44 +-
.../http/compression/CompressedResponsesTest.java | 11 +-
.../endtoend/logging/VirtualHostLoggerTest.java | 6 +-
.../message/CompressedMessageContentTest.java | 11 +-
.../endtoend/message/ExportImportMessagesTest.java | 11 +-
.../endtoend/message/MessageManagementTest.java | 7 +-
.../tests/http/endtoend/message/MessageTest.java | 17 +-
.../http/endtoend/message/TimeToLiveTest.java | 14 +-
.../tests/http/endtoend/port/HttpPortTest.java | 11 +-
.../qpid/tests/http/endtoend/port/PortTest.java | 21 +-
.../endtoend/state/VirtualHostRecoveryTest.java | 18 +-
.../statistics/StatisticsReportingTest.java | 3 +-
.../tests/http/endtoend/store/SpiltStoreTest.java | 21 +-
.../metrics/BrokerMetricsAuthenticationTest.java | 3 +-
.../qpid/tests/http/metrics/BrokerMetricsTest.java | 2 +-
.../qpid/tests/http/metrics/TestMetricsHelper.java | 2 +-
.../tests/http/metrics/VirtualHostMetricsTest.java | 2 +-
.../qpid/tests/http/query/QueryBrokerTest.java | 3 +-
.../qpid/tests/http/rest/model/CreateTest.java | 3 +-
.../qpid/tests/http/rest/model/DeleteTest.java | 9 +-
.../qpid/tests/http/rest/model/OperationTest.java | 9 +-
.../qpid/tests/http/rest/model/ReadTest.java | 6 +-
.../qpid/tests/http/rest/model/UpdateTest.java | 6 +-
.../qpid/tests/http/service/StructureTest.java | 56 +-
.../qpid/tests/http/transport/UnifiedPortTest.java | 3 +-
.../http/userprefs/UserPreferencesRestTest.java | 169 +--
.../apache/qpid/tests/http/v6_1/BindingTest.java | 7 +-
.../qpid/tests/http/v7_0/LegacyManagementTest.java | 7 +-
.../qpid/tests/http/v8_0/LegacyManagementTest.java | 2 +-
.../java/org/apache/qpid/systests/JmsTestBase.java | 13 +-
.../qpid/systests/QpidJmsClient0xProvider.java | 3 -
.../main/java/org/apache/qpid/systests/Utils.java | 1 -
.../jms_1_1/acknowledge/AcknowledgeTest.java | 35 +-
.../systests/jms_1_1/acknowledge/RecoverTest.java | 29 +-
.../qpid/systests/jms_1_1/browser/BrowserTest.java | 32 +-
.../connection/AbruptClientDisconnectTest.java | 45 +-
.../jms_1_1/connection/ConnectionStartTest.java | 22 +-
.../jms_1_1/connection/ConnectionTest.java | 4 +-
.../jms_1_1/connection/ExceptionListenerTest.java | 45 +-
.../connection/SpontaneousConnectionCloseTest.java | 15 +-
.../qpid/systests/jms_1_1/consumer/DupsOkTest.java | 24 +-
.../jms_1_1/consumer/SynchReceiveTest.java | 20 +-
.../jms_1_1/extensions/BrokerManagementHelper.java | 4 +-
.../jms_1_1/extensions/acl/MessagingACLTest.java | 56 +-
.../autocreation/DefaultAlternateBindingTest.java | 7 +-
.../autocreation/NodeAutoCreationPolicyTest.java | 39 +-
.../compression/MessageCompressionTest.java | 33 +-
.../MessagingConnectionLimitTest.java | 7 +-
.../consumerpriority/ConsumerPriorityTest.java | 80 +-
.../extensions/filters/ArrivalTimeFilterTest.java | 51 +-
.../extensions/filters/DefaultFiltersTest.java | 20 +-
.../limitliveconsumers/LimitLiveConsumersTest.java | 36 +-
.../extensions/management/AmqpManagementTest.java | 240 ++--
.../extensions/maxdelivery/MaxDeliveryTest.java | 48 +-
.../ObjectMessageClassAllowlistingTest.java | 44 +-
.../EnsureNondestructiveConsumersTest.java | 29 +-
.../jms_1_1/extensions/prefetch/PrefetchTest.java | 38 +-
.../extensions/queue/LastValueQueueTest.java | 116 +-
.../extensions/queue/OverflowPolicyTestBase.java | 11 +-
.../extensions/queue/PriorityQueueTest.java | 39 +-
.../extensions/queue/ProducerFlowControlTest.java | 128 +-
.../queue/QueueMessageDurabilityTest.java | 25 +-
.../jms_1_1/extensions/queue/QueuePolicyTest.java | 36 +-
.../extensions/queue/RejectOverflowPolicyTest.java | 14 +-
.../jms_1_1/extensions/queue/SortedQueueTest.java | 54 +-
.../extensions/queue/TemporaryQueuePrefixTest.java | 27 +-
.../routing/AlternateBindingRoutingTest.java | 25 +-
.../extensions/routing/ExchangeRoutingTest.java | 25 +-
.../extensions/routing/MessageRoutingTest.java | 36 +-
.../extensions/sasl/AuthenticationTest.java | 53 +-
.../systests/jms_1_1/extensions/tls/TlsTest.java | 46 +-
.../transactiontimeout/TransactionTimeoutTest.java | 13 +-
.../systests/jms_1_1/message/BytesMessageTest.java | 18 +-
.../jms_1_1/message/ForeignMessageTest.java | 30 +-
.../jms_1_1/message/JMSDestinationTest.java | 68 +-
.../message/JMSHeadersAndPropertiesTest.java | 108 +-
.../systests/jms_1_1/message/JMSReplyToTest.java | 24 +-
.../systests/jms_1_1/message/LargeMessageTest.java | 13 +-
.../systests/jms_1_1/message/MapMessageTest.java | 24 +-
.../jms_1_1/message/ObjectMessageTest.java | 106 +-
.../jms_1_1/message/StreamMessageTest.java | 18 +-
.../systests/jms_1_1/message/TextMessageTest.java | 16 +-
.../systests/jms_1_1/message/TimeToLiveTest.java | 34 +-
.../jms_1_1/messagegroup/MessageGroupTest.java | 124 +-
.../messagelistener/MessageListenerTest.java | 40 +-
.../persistence/PersistentMessagingTest.java | 50 +-
.../jms_1_1/producer/AnonymousProducerTest.java | 23 +-
.../jms_1_1/producer/MessageProducerTest.java | 13 +-
.../systests/jms_1_1/queue/TemporaryQueueTest.java | 39 +-
.../jms_1_1/queueconnection/QueueReceiverTest.java | 15 +-
.../jms_1_1/queueconnection/QueueSenderTest.java | 7 +-
.../jms_1_1/queueconnection/QueueSessionTest.java | 7 +-
.../systests/jms_1_1/selector/SelectorTest.java | 25 +-
...btionTest.java => DurableSubscriptionTest.java} | 86 +-
.../systests/jms_1_1/topic/TemporaryTopicTest.java | 23 +-
.../jms_1_1/topic/TopicSubscriberTest.java | 33 +-
.../jms_1_1/topicconnection/TopicSessionTest.java | 5 +-
.../jms_1_1/transaction/CommitRollbackTest.java | 164 ++-
.../jms_2_0/connection/ConnectionTest.java | 5 +-
.../jms_2_0/deliverycount/DeliveryCountTest.java | 29 +-
.../jms_2_0/deliverydelay/DeliveryDelayTest.java | 46 +-
.../subscription/SharedSubscriptionTest.java | 88 +-
.../qpid/systests/admin/SpawnBrokerAdminTest.java | 20 +-
.../qpid/tests/utils/BrokerAdminUsingTestBase.java | 29 +-
.../apache/qpid/tests/utils/QpidTestExtension.java | 114 ++
.../apache/qpid/tests/utils/QpidTestRunner.java | 101 --
.../qpid/tests/utils/BrokerAdminFactoryTest.java | 10 +-
.../utils/ExternalQpidBrokerAdminImplTest.java | 9 +-
.../qpid/tests/utils/NoOpQueueAdminTest.java | 9 +-
.../qpid/tests/utils/QueueAdminFactoryTest.java | 14 +-
794 files changed, 20995 insertions(+), 27067 deletions(-)
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncodingTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncodingTest.java
index 991ece2c06..0722f9f107 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncodingTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncodingTest.java
@@ -18,24 +18,23 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.protocol.v0_8.AMQShortString;
import org.apache.qpid.test.utils.UnitTestBase;
-
/**
* Tests for {@code AMQShortStringEncoding} including corner cases when string
* is null or over 127 characters in length
*/
public class AMQShortStringEncodingTest extends UnitTestBase
{
-
@Test
public void testWriteReadNullValues()
{
@@ -47,7 +46,7 @@ public class AMQShortStringEncodingTest extends UnitTestBase
// read from tuple input
TupleInput tupleInput = new TupleInput(data);
AMQShortString result = AMQShortStringEncoding.readShortString(tupleInput);
- assertNull("Expected null but got " + result, result);
+ assertNull(result, "Expected null but got " + result);
}
@Test
@@ -63,7 +62,7 @@ public class AMQShortStringEncodingTest extends UnitTestBase
// read from tuple input
TupleInput tupleInput = new TupleInput(data);
AMQShortString result = AMQShortStringEncoding.readShortString(tupleInput);
- assertEquals("Expected " + value + " but got " + result, value, result);
+ assertEquals(value, result, "Expected " + value + " but got " + result);
}
@Test
@@ -79,7 +78,7 @@ public class AMQShortStringEncodingTest extends UnitTestBase
// read from tuple input
TupleInput tupleInput = new TupleInput(data);
AMQShortString result = AMQShortStringEncoding.readShortString(tupleInput);
- assertEquals("Expected " + value + " but got " + result, value, result);
+ assertEquals(value, result, "Expected " + value + " but got " + result);
}
private AMQShortString createString(char ch, int length)
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBHAVirtualHostNodeTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBHAVirtualHostNodeTest.java
index 435dda47c9..abfe7eee67 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBHAVirtualHostNodeTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBHAVirtualHostNodeTest.java
@@ -20,15 +20,13 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.when;
import java.io.File;
@@ -50,9 +48,10 @@ import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.rep.NoConsistencyRequiredPolicy;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.ReplicationConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -83,17 +82,19 @@ import org.apache.qpid.test.utils.VirtualHostNodeStoreType;
public class BDBHAVirtualHostNodeTest extends UnitTestBase
{
private final static Logger LOGGER = LoggerFactory.getLogger(BDBHAVirtualHostNodeTest.class);
- private final PortHelper _portHelper = new PortHelper();
+
private BDBHAVirtualHostNodeTestHelper _helper;
+ private final PortHelper _portHelper = new PortHelper();
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(VirtualHostNodeStoreType.BDB.equals(getVirtualHostNodeStoreType()),
+ "VirtualHostNodeStoreType should be BDB");
_helper = new BDBHAVirtualHostNodeTestHelper(getTestName());
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -131,7 +132,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
catch (RuntimeException e)
{
final boolean condition = e.getCause() instanceof IllegalArgumentException;
- assertTrue("Unexpected Exception being thrown.", condition);
+ assertTrue(condition, "Unexpected Exception being thrown.");
}
context.put(EnvironmentConfig.ENV_IS_TRANSACTIONAL, "true");
BDBHAVirtualHostNode<?> node = _helper.createHaVHN(attributes);
@@ -139,7 +140,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
node.start();
_helper.assertNodeRole(node, NodeRole.MASTER, NodeRole.REPLICA);
- assertEquals("Unexpected node state", State.ACTIVE, node.getState());
+ assertEquals(State.ACTIVE, node.getState(), "Unexpected node state");
DurableConfigurationStore store = node.getConfigurationStore();
assertNotNull(store);
@@ -147,7 +148,6 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
BDBConfigurationStore bdbConfigurationStore = (BDBConfigurationStore) store;
ReplicatedEnvironmentFacade environmentFacade = (ReplicatedEnvironmentFacade) bdbConfigurationStore.getEnvironmentFacade();
-
assertEquals(nodeName, environmentFacade.getNodeName());
assertEquals(groupName, environmentFacade.getGroupName());
assertEquals(helperAddress, environmentFacade.getHostPort());
@@ -157,23 +157,22 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
_helper.awaitForVirtualhost(node);
VirtualHost<?> virtualHost = node.getVirtualHost();
- assertNotNull("Virtual host child was not added", virtualHost);
- assertEquals("Unexpected virtual host name", groupName, virtualHost.getName());
- assertEquals("Unexpected virtual host store",
- bdbConfigurationStore.getMessageStore(),
- virtualHost.getMessageStore());
- assertEquals("Unexpected virtual host state", State.ACTIVE, virtualHost.getState());
+ assertNotNull(virtualHost, "Virtual host child was not added");
+ assertEquals(groupName, virtualHost.getName(), "Unexpected virtual host name");
+ assertEquals(bdbConfigurationStore.getMessageStore(), virtualHost.getMessageStore(),
+ "Unexpected virtual host store");
+ assertEquals(State.ACTIVE, virtualHost.getState(), "Unexpected virtual host state");
node.stop();
- assertEquals("Unexpected state returned after stop", State.STOPPED, node.getState());
- assertEquals("Unexpected state", State.STOPPED, node.getState());
+ assertEquals(State.STOPPED, node.getState(), "Unexpected state returned after stop");
+ assertEquals(State.STOPPED, node.getState(), "Unexpected state");
- assertNull("Virtual host is not destroyed", node.getVirtualHost());
+ assertNull(node.getVirtualHost(), "Virtual host is not destroyed");
node.delete();
- assertEquals("Unexpected state returned after delete", State.DELETED, node.getState());
- assertEquals("Unexpected state", State.DELETED, node.getState());
- assertFalse("Store still exists " + messageStorePath, new File(messageStorePath).exists());
+ assertEquals(State.DELETED, node.getState(), "Unexpected state returned after delete");
+ assertEquals(State.DELETED, node.getState(), "Unexpected state");
+ assertFalse(new File(messageStorePath).exists(), "Store still exists " + messageStorePath);
}
@Test
@@ -187,11 +186,10 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Map<String, Object> attributes = _helper.createNodeAttributes(nodeName, groupName, helperAddress, helperAddress, nodeName, node1PortNumber);
BDBHAVirtualHostNode<?> node = _helper.createAndStartHaVHN(attributes);
- assertEquals("Unexpected node priority value before mutation", (long) 1, (long) node.getPriority());
- assertFalse("Unexpected designated primary value before mutation", node.isDesignatedPrimary());
- assertEquals("Unexpected electable group override value before mutation",
- (long) 0,
- (long) node.getQuorumOverride());
+ assertEquals(1, (long) node.getPriority(), "Unexpected node priority value before mutation");
+ assertFalse(node.isDesignatedPrimary(), "Unexpected designated primary value before mutation");
+ assertEquals(0, (long) node.getQuorumOverride(),
+ "Unexpected electable group override value before mutation");
Map<String, Object> update = new HashMap<>();
update.put(BDBHAVirtualHostNode.PRIORITY, 2);
@@ -199,15 +197,14 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
update.put(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1);
node.setAttributes(update);
- assertEquals("Unexpected node priority value after mutation", (long) 2, (long) node.getPriority());
- assertTrue("Unexpected designated primary value after mutation", node.isDesignatedPrimary());
- assertEquals("Unexpected electable group override value after mutation",
- (long) 1,
- (long) node.getQuorumOverride());
+ assertEquals(2, (long) node.getPriority(), "Unexpected node priority value after mutation");
+ assertTrue(node.isDesignatedPrimary(), "Unexpected designated primary value after mutation");
+ assertEquals(1, (long) node.getQuorumOverride(),
+ "Unexpected electable group override value after mutation");
- assertNotNull("Join time should be set", node.getJoinTime());
- assertNotNull("Last known replication transaction id should be set",
- node.getLastKnownReplicationTransactionId());
+ assertNotNull(node.getJoinTime(), "Join time should be set");
+ assertNotNull(node.getLastKnownReplicationTransactionId(),
+ "Last known replication transaction id should be set");
}
@Test
@@ -230,11 +227,10 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Map<String, Object> node3Attributes = _helper.createNodeAttributes("node3", groupName, "localhost:" + node3PortNumber, helperAddress, nodeName);
BDBHAVirtualHostNode<?> node3 = _helper.createAndStartHaVHN(node3Attributes);
- assertEquals("Unexpected node priority value before mutation", (long) 1, (long) node1.getPriority());
- assertFalse("Unexpected designated primary value before mutation", node1.isDesignatedPrimary());
- assertEquals("Unexpected electable group override value before mutation",
- (long) 0,
- (long) node1.getQuorumOverride());
+ assertEquals(1, (long) node1.getPriority(), "Unexpected node priority value before mutation");
+ assertFalse(node1.isDesignatedPrimary(), "Unexpected designated primary value before mutation");
+ assertEquals(0, (long) node1.getQuorumOverride(),
+ "Unexpected electable group override value before mutation");
node2.close();
node3.close();
@@ -249,11 +245,10 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
_helper.awaitForVirtualhost(node1);
- assertEquals("Unexpected node priority value after mutation", (long) 200, (long) node1.getPriority());
- assertTrue("Unexpected designated primary value after mutation", node1.isDesignatedPrimary());
- assertEquals("Unexpected electable group override value after mutation",
- (long) 1,
- (long) node1.getQuorumOverride());
+ assertEquals(200, (long) node1.getPriority(), "Unexpected node priority value after mutation");
+ assertTrue(node1.isDesignatedPrimary(), "Unexpected designated primary value after mutation");
+ assertEquals(1, (long) node1.getQuorumOverride(),
+ "Unexpected electable group override value after mutation");
}
@Test
@@ -278,7 +273,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
BDBHAVirtualHostNode<?> replica = _helper.awaitAndFindNodeInRole(NodeRole.REPLICA);
- replica.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.ROLE, NodeRole.MASTER));
+ replica.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.ROLE, NodeRole.MASTER));
_helper.assertNodeRole(replica, NodeRole.MASTER);
}
@@ -319,12 +314,13 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Map<String, Object> node3Attributes = _helper.createNodeAttributes("node3", groupName, "localhost:" + node3PortNumber, helperAddress, nodeName);
BDBHAVirtualHostNode<?> node3 = _helper.createAndStartHaVHN(node3Attributes);
- assertTrue("Replication nodes have not been seen during 5s", remoteNodeLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(remoteNodeLatch.await(5, TimeUnit.SECONDS),
+ "Replication nodes have not been seen during 5s");
BDBHARemoteReplicationNodeImpl replicaRemoteNode = (BDBHARemoteReplicationNodeImpl)lastSeenReplica.get();
_helper.awaitForAttributeChange(replicaRemoteNode, BDBHARemoteReplicationNodeImpl.ROLE, NodeRole.REPLICA);
- replicaRemoteNode.setAttributes(Collections.<String,Object>singletonMap(BDBHARemoteReplicationNode.ROLE, NodeRole.MASTER));
+ replicaRemoteNode.setAttributes(Collections.singletonMap(BDBHARemoteReplicationNode.ROLE, NodeRole.MASTER));
BDBHAVirtualHostNode<?> replica = replicaRemoteNode.getName().equals(node2.getName())? node2 : node3;
_helper.assertNodeRole(replica, NodeRole.MASTER);
@@ -344,7 +340,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
try
{
- node.setAttributes(Collections.<String,Object>singletonMap(BDBHAVirtualHostNode.ROLE, NodeRole.REPLICA));
+ node.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.ROLE, NodeRole.REPLICA));
fail("Role mutation should fail");
}
catch(IllegalStateException e)
@@ -387,14 +383,14 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
BDBHAVirtualHostNode<?> replica = _helper.awaitAndFindNodeInRole(NodeRole.REPLICA);
_helper.awaitRemoteNodes(replica, 2);
- assertNotNull("Remote node " + replica.getName() + " is not found",
- _helper.findRemoteNode(master, replica.getName()));
+ assertNotNull(_helper.findRemoteNode(master, replica.getName()),
+ "Remote node " + replica.getName() + " is not found");
replica.delete();
_helper.awaitRemoteNodes(master, 1);
- assertNull("Remote node " + replica.getName() + " is not found",
- _helper.findRemoteNode(master, replica.getName()));
+ assertNull(_helper.findRemoteNode(master, replica.getName()),
+ "Remote node " + replica.getName() + " is not found");
}
@@ -411,23 +407,21 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
node.start();
_helper.assertNodeRole(node, NodeRole.MASTER, NodeRole.REPLICA);
- assertEquals("Unexpected node state", State.ACTIVE, node.getState());
+ assertEquals(State.ACTIVE, node.getState(), "Unexpected node state");
_helper.awaitForVirtualhost(node);
BDBHAVirtualHostImpl virtualHost = (BDBHAVirtualHostImpl)node.getVirtualHost();
- assertNotNull("Virtual host is not created", virtualHost);
+ assertNotNull(virtualHost, "Virtual host is not created");
_helper.awaitForAttributeChange(virtualHost, BDBHAVirtualHostImpl.COALESCING_SYNC, true);
- assertEquals("Unexpected local transaction synchronization policy",
- "SYNC",
- virtualHost.getLocalTransactionSynchronizationPolicy());
- assertEquals("Unexpected remote transaction synchronization policy",
- "NO_SYNC",
- virtualHost.getRemoteTransactionSynchronizationPolicy());
- assertTrue("CoalescingSync is not ON", virtualHost.isCoalescingSync());
+ assertEquals("SYNC", virtualHost.getLocalTransactionSynchronizationPolicy(),
+ "Unexpected local transaction synchronization policy");
+ assertEquals("NO_SYNC", virtualHost.getRemoteTransactionSynchronizationPolicy(),
+ "Unexpected remote transaction synchronization policy");
+ assertTrue(virtualHost.isCoalescingSync(), "CoalescingSync is not ON");
- Map<String, Object> virtualHostAttributes = new HashMap<String,Object>();
+ Map<String, Object> virtualHostAttributes = new HashMap<>();
virtualHostAttributes.put(BDBHAVirtualHost.LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY, "WRITE_NO_SYNC");
virtualHostAttributes.put(BDBHAVirtualHost.REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY, "SYNC");
virtualHost.setAttributes(virtualHostAttributes);
@@ -435,16 +429,14 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
virtualHost.stop();
virtualHost.start();
- assertEquals("Unexpected local transaction synchronization policy",
- "WRITE_NO_SYNC",
- virtualHost.getLocalTransactionSynchronizationPolicy());
- assertEquals("Unexpected remote transaction synchronization policy",
- "SYNC",
- virtualHost.getRemoteTransactionSynchronizationPolicy());
- assertFalse("CoalescingSync is not OFF", virtualHost.isCoalescingSync());
+ assertEquals("WRITE_NO_SYNC", virtualHost.getLocalTransactionSynchronizationPolicy(),
+ "Unexpected local transaction synchronization policy");
+ assertEquals("SYNC", virtualHost.getRemoteTransactionSynchronizationPolicy(),
+ "Unexpected remote transaction synchronization policy");
+ assertFalse(virtualHost.isCoalescingSync(), "CoalescingSync is not OFF");
try
{
- virtualHost.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHost.LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY, "INVALID"));
+ virtualHost.setAttributes(Collections.singletonMap(BDBHAVirtualHost.LOCAL_TRANSACTION_SYNCHRONIZATION_POLICY, "INVALID"));
fail("Invalid synchronization policy is set");
}
catch(IllegalArgumentException e)
@@ -454,7 +446,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
try
{
- virtualHost.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHost.REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY, "INVALID"));
+ virtualHost.setAttributes(Collections.singletonMap(BDBHAVirtualHost.REMOTE_TRANSACTION_SYNCHRONIZATION_POLICY, "INVALID"));
fail("Invalid synchronization policy is set");
}
catch(IllegalArgumentException e)
@@ -490,9 +482,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch(IllegalConfigurationException e)
{
- assertEquals("Unexpected exception message",
- String.format("Node using address '%s' is not permitted to join the group 'group'", "localhost:" + node3PortNumber, groupName),
- e.getMessage());
+ assertEquals(String.format("Node using address '%s' is not permitted to join the group 'group'",
+ "localhost:" + node3PortNumber), e.getMessage(), "Unexpected exception message");
}
}
@@ -534,9 +525,9 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch(IllegalArgumentException e)
{
- assertEquals("Unexpected exception message",
- String.format("The current group node '%s' cannot be removed from '%s' as its already a group member", node3Address, BDBHAVirtualHostNode.PERMITTED_NODES),
- e.getMessage());
+ assertEquals(String.format("The current group node '%s' cannot be removed from '%s' as its already a group member", node3Address, BDBHAVirtualHostNode.PERMITTED_NODES),
+ e.getMessage(),
+ "Unexpected exception message");
}
}
@@ -580,24 +571,24 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
BDBHAVirtualHostNode<?> nonMasterNode = _helper.findNodeInRole(NodeRole.REPLICA);
try
{
- nonMasterNode.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
+ nonMasterNode.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
fail("Operation to update permitted nodes should have failed from non MASTER node");
}
catch(IllegalArgumentException e)
{
- assertEquals("Unexpected exception message",
- String.format("Attribute '%s' can only be set on '%s' node or node in '%s' or '%s' state", BDBHAVirtualHostNode.PERMITTED_NODES, NodeRole.MASTER, State.STOPPED, State.ERRORED),
- e.getMessage());
+ assertEquals(String.format("Attribute '%s' can only be set on '%s' node or node in '%s' or '%s' state", BDBHAVirtualHostNode.PERMITTED_NODES, NodeRole.MASTER, State.STOPPED, State.ERRORED),
+ e.getMessage(),
+ "Unexpected exception message");
}
// Try to update the permitted nodes attributes using the new list on MASTER - should succeed
BDBHAVirtualHostNode<?> masterNode = _helper.findNodeInRole(NodeRole.MASTER);
- masterNode.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
+ masterNode.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
// Try to update the permitted nodes attributes using the new list on a STOPPED node - should succeed
nonMasterNode.stop();
amendedPermittedNodes.add(node5Address);
- nonMasterNode.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
+ nonMasterNode.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, amendedPermittedNodes));
}
@Test
@@ -630,8 +621,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Durability durability = Durability.parse((String) node1Attributes.get(BDBHAVirtualHostNode.DURABILITY));
joinIntruder(intruderPortNumber, "intruder", groupName, helperAddress, durability, environmentPathFile);
- assertTrue("Intruder protection was not triggered during expected timeout",
- stopLatch.await(10, TimeUnit.SECONDS));
+ assertTrue(stopLatch.await(10, TimeUnit.SECONDS),
+ "Intruder protection was not triggered during expected timeout");
final CountDownLatch stateChangeLatch = new CountDownLatch(1);
final CountDownLatch roleChangeLatch = new CountDownLatch(1);
@@ -659,7 +650,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
});
- // Try top re start the ERRORED node and ensure exception is thrown
+ // Try top restart the ERRORED node and ensure exception is thrown
try
{
node.start();
@@ -667,14 +658,14 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch (IllegalStateException ise)
{
- assertEquals("Unexpected exception when restarting node post intruder detection",
- "Intruder node detected: " + "localhost:" + intruderPortNumber,
- ise.getMessage());
+ assertEquals("Intruder node detected: " + "localhost:" + intruderPortNumber,
+ ise.getMessage(),
+ "Unexpected exception when restarting node post intruder detection");
}
// verify that intruder detection is triggered after restart and environment is closed
- assertTrue("Node state was not set to ERRORED", stateChangeLatch.await(10, TimeUnit.SECONDS));
- assertTrue("Node role was not set to DETACHED", roleChangeLatch.await(10, TimeUnit.SECONDS));
+ assertTrue(stateChangeLatch.await(10, TimeUnit.SECONDS), "Node state was not set to ERRORED");
+ assertTrue(roleChangeLatch.await(10, TimeUnit.SECONDS), "Node role was not set to DETACHED");
}
@Test
@@ -715,8 +706,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
LOGGER.debug("Permitted and intruder nodes are created");
- assertTrue("Intruder protection was not triggered during expected timeout",
- stopLatch.await(10, TimeUnit.SECONDS));
+ assertTrue(stopLatch.await(10, TimeUnit.SECONDS),
+ "Intruder protection was not triggered during expected timeout");
LOGGER.debug("Master node transited into ERRORED state due to intruder protection");
when(_helper.getBroker().isManagementMode()).thenReturn(true);
@@ -752,8 +743,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
LOGGER.debug("Node is started");
// verify that intruder detection is triggered after restart and environment is closed
- assertTrue("Node state was not set to ERRORED", stateChangeLatch.await(10, TimeUnit.SECONDS));
- assertTrue("Node role was not set to DETACHED", roleChangeLatch.await(10, TimeUnit.SECONDS));
+ assertTrue(stateChangeLatch.await(10, TimeUnit.SECONDS), "Node state was not set to ERRORED");
+ assertTrue(roleChangeLatch.await(10, TimeUnit.SECONDS), "Node role was not set to DETACHED");
}
@Test
@@ -772,7 +763,7 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Map<String, Object> node2Attributes = _helper.createNodeAttributes("node2", groupName, "localhost:" + node2PortNumber, helperAddress, nodeName);
node2Attributes.put(BDBHAVirtualHostNode.PRIORITY, 0);
BDBHAVirtualHostNode<?> node2 = _helper.createAndStartHaVHN(node2Attributes);
- assertEquals("Unexpected role", NodeRole.REPLICA, node2.getRole());
+ assertEquals(NodeRole.REPLICA, node2.getRole(), "Unexpected role");
_helper.awaitRemoteNodes(node2, 1);
BDBHARemoteReplicationNode<?> remote = _helper.findRemoteNode(node2, node1.getName());
@@ -793,29 +784,23 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
});
List<String> permittedNodes = new ArrayList<>(node1.getPermittedNodes());
permittedNodes.add("localhost:5000");
- node1.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, permittedNodes));
+ node1.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, permittedNodes));
- assertTrue("Permitted nodes were not changed on Replica",
- _permittedNodesLatch.await(10, TimeUnit.SECONDS));
- assertEquals("Not the same permitted nodes",
- new HashSet<>(node1.getPermittedNodes()),
- new HashSet<>(node2.getPermittedNodes()));
- assertEquals("Unexpected counter of changes permitted nodes",
- (long) 1,
- (long) permittedNodesChangeCounter.get());
+ assertTrue(_permittedNodesLatch.await(10, TimeUnit.SECONDS), "Permitted nodes were not changed on Replica");
+ assertEquals(new HashSet<>(node1.getPermittedNodes()), new HashSet<>(node2.getPermittedNodes()),
+ "Not the same permitted nodes");
+ assertEquals(1, (long) permittedNodesChangeCounter.get(), "Unexpected counter of changes permitted nodes");
// change the order of permitted nodes
Collections.swap(permittedNodes, 0, 2);
- node1.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, permittedNodes));
+ node1.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PERMITTED_NODES, permittedNodes));
// make sure that node2 onNodeState was invoked by performing transaction on master and making sure that it was replicated
performTransactionAndAwaitForRemoteNodeToGetAware(node1, remote);
// perform transaction second time because permitted nodes are changed after last transaction id
performTransactionAndAwaitForRemoteNodeToGetAware(node1, remote);
- assertEquals("Unexpected counter of changes permitted nodes",
- (long) 1,
- (long) permittedNodesChangeCounter.get());
+ assertEquals(1, (long) permittedNodesChangeCounter.get(), "Unexpected counter of changes permitted nodes");
}
private void performTransactionAndAwaitForRemoteNodeToGetAware(BDBHAVirtualHostNode<?> node1, BDBHARemoteReplicationNode<?> remote) throws InterruptedException
@@ -827,9 +812,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
{
Thread.sleep(100L);
}
- assertEquals("Last transaction was not replicated",
- Long.valueOf(remote.getLastKnownReplicationTransactionId()),
- node1.getLastKnownReplicationTransactionId());
+ assertEquals(Long.valueOf(remote.getLastKnownReplicationTransactionId()), node1.getLastKnownReplicationTransactionId(),
+ "Last transaction was not replicated");
}
@Test
@@ -864,8 +848,8 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
Durability durability = Durability.parse((String) node1Attributes.get(BDBHAVirtualHostNode.DURABILITY));
joinIntruder(node2PortNumber, node2Name, groupName, helperAddress, durability, environmentPathFile);
- assertTrue("Intruder protection was not triggered during expected timeout",
- stopLatch.await(20, TimeUnit.SECONDS));
+ assertTrue(stopLatch.await(20, TimeUnit.SECONDS),
+ "Intruder protection was not triggered during expected timeout");
}
private void joinIntruder(final int nodePortNumber,
@@ -924,9 +908,9 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch(ExternalServiceException e)
{
- assertEquals("Unexpected exception on connection to non-existing helper address",
- String.format("Cannot connect to existing node '%s' at '%s'", "node2", "localhost:" + node2PortNumber),
- e.getMessage());
+ assertEquals(String.format("Cannot connect to existing node '%s' at '%s'", "node2", "localhost:" + node2PortNumber),
+ e.getMessage(),
+ "Unexpected exception on connection to non-existing helper address");
}
}
@@ -948,9 +932,9 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch(IllegalConfigurationException e)
{
- assertEquals("Unexpected exception on attempt to create node with already bound address",
- String.format("Cannot bind to address '%s'. Address is already in use.", "localhost:" + node1PortNumber),
- e.getMessage());
+ assertEquals(String.format("Cannot bind to address '%s'. Address is already in use.", "localhost:" + node1PortNumber),
+ e.getMessage(),
+ "Unexpected exception on attempt to create node with already bound address");
}
}
}
@@ -976,9 +960,9 @@ public class BDBHAVirtualHostNodeTest extends UnitTestBase
}
catch (IllegalConfigurationException e)
{
- assertEquals("Unexpected exception on attempt to create environment in invalid location",
- String.format("Store path '%s' is not a folder", storePath.getAbsoluteFile()),
- e.getMessage());
+ assertEquals(String.format("Store path '%s' is not a folder", storePath.getAbsoluteFile()),
+ e.getMessage(),
+ "Unexpected exception on attempt to create environment in invalid location");
}
}
finally
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java
index 15ddaefdc2..e4a73871cb 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java
@@ -20,13 +20,11 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
import org.apache.qpid.server.model.ConfiguredObjectFactory;
import org.apache.qpid.server.model.VirtualHost;
@@ -38,11 +36,12 @@ import org.apache.qpid.test.utils.VirtualHostNodeStoreType;
public class BDBMessageStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase
{
- @Before
+ @BeforeEach
@Override
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(getVirtualHostNodeStoreType().equals(VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
super.setUp();
}
@@ -55,7 +54,7 @@ public class BDBMessageStoreConfigurationTest extends AbstractDurableConfigurati
}
@Override
- protected DurableConfigurationStore createConfigStore() throws Exception
+ protected DurableConfigurationStore createConfigStore()
{
return new BDBConfigurationStore(VirtualHost.class);
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreQuotaEventsTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreQuotaEventsTest.java
index 8fb41e81dc..dd6e14aaaf 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreQuotaEventsTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreQuotaEventsTest.java
@@ -20,9 +20,7 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -30,7 +28,7 @@ import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Map;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
import org.apache.qpid.server.model.VirtualHost;
import org.apache.qpid.server.store.MessageStore;
@@ -64,11 +62,12 @@ public class BDBMessageStoreQuotaEventsTest extends MessageStoreQuotaEventsTestB
return NUMBER_OF_MESSAGES_TO_OVERFILL_STORE;
}
- @Before
+ @BeforeEach
@Override
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(getVirtualHostNodeStoreType().equals(VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
super.setUp();
}
@@ -90,7 +89,6 @@ public class BDBMessageStoreQuotaEventsTest extends MessageStoreQuotaEventsTestB
@Override
protected MessageStore createStore() throws Exception
{
- MessageStore store = new BDBMessageStore();
- return store;
+ return new BDBMessageStore();
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
index 551c5e0807..9f747cebe5 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
@@ -22,27 +22,23 @@ package org.apache.qpid.server.store.berkeleydb;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Collections;
import com.sleepycat.je.LockTimeoutException;
-import com.sleepycat.je.Sequence;
-import org.junit.Test;
-import org.mockito.Mockito;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
import org.apache.qpid.server.message.internal.InternalMessageMetaData;
@@ -74,13 +70,16 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
private String _storeLocation;
@Override
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(is(equalTo(VirtualHostNodeStoreType.BDB)).matches(VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
super.setUp();
}
@Override
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -121,7 +120,7 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
* expected exceptions are thrown to indicate the message is not present.
*/
@Test
- public void testMessageCreationAndRemoval() throws Exception
+ public void testMessageCreationAndRemoval()
{
BDBMessageStore bdbStore = (BDBMessageStore) getStore();
@@ -175,15 +174,15 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
}
@Test
- public void testOnDelete() throws Exception
+ public void testOnDelete()
{
String storeLocation = getStore().getStoreLocation();
File location = new File(storeLocation);
- assertTrue("Store does not exist at " + storeLocation, location.exists());
+ assertTrue(location.exists(), "Store does not exist at " + storeLocation);
getStore().closeMessageStore();
- assertTrue("Store does not exist at " + storeLocation, location.exists());
+ assertTrue(location.exists(), "Store does not exist at " + storeLocation);
BDBVirtualHost mockVH = mock(BDBVirtualHost.class);
String testLocation = getStore().getStoreLocation();
@@ -191,7 +190,7 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
getStore().onDelete(mockVH);
- assertFalse("Store exists at " + storeLocation, location.exists());
+ assertFalse(location.exists(), "Store exists at " + storeLocation);
}
@@ -235,7 +234,7 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
EnvironmentFacadeFactory eff = mock(EnvironmentFacadeFactory.class);
EnvironmentFacade ef = mock(EnvironmentFacade.class);
doThrow(LockTimeoutException.class).when(ef).openSequence(any(),any(),any());
- when(((EnvironmentFacadeFactory) eff).createEnvironmentFacade(any())).thenReturn(ef);
+ when(eff.createEnvironmentFacade(any())).thenReturn(ef);
BDBMessageStore store = new BDBMessageStore (eff);
store.openMessageStore(getVirtualHost());
@@ -247,7 +246,7 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
}
catch(ConnectionScopedRuntimeException e)
{
- assertEquals("Unexpected exception on BDB sequence",e.getMessage());
+ assertEquals("Unexpected exception on BDB sequence", e.getMessage());
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBPreferenceStoreTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBPreferenceStoreTest.java
index 5e050185d7..06c9385381 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBPreferenceStoreTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBPreferenceStoreTest.java
@@ -19,15 +19,12 @@
package org.apache.qpid.server.store.berkeleydb;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,6 +35,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.Objects;
import java.util.UUID;
import com.sleepycat.bind.tuple.ByteBinding;
@@ -47,9 +45,10 @@ import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.BrokerModel;
import org.apache.qpid.server.model.ConfiguredObject;
@@ -71,30 +70,31 @@ public class BDBPreferenceStoreTest extends UnitTestBase
private BDBPreferenceStore _preferenceStore;
private List<PreferenceRecord> _testInitialRecords;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_storeFile = new File(TMP_FOLDER, getTestName() + System.currentTimeMillis() + ".preferences.bdb");
boolean result = _storeFile.mkdirs();
- assertTrue(String.format("Test folder '%s' was not created", _storeFile.getAbsolutePath()), result);
+ assertTrue(result, String.format("Test folder '%s' was not created", _storeFile.getAbsolutePath()));
_updater = mock(PreferenceStoreUpdater.class);
when(_updater.getLatestVersion()).thenReturn(BrokerModel.MODEL_VERSION);
final ConfiguredObject<?> parent = mock(ConfiguredObject.class);
- when(parent.getContext()).thenReturn(Collections.<String, String>emptyMap());
- when(parent.getContextKeys(anyBoolean())).thenReturn(Collections.<String>emptySet());
+ when(parent.getContext()).thenReturn(Collections.emptyMap());
+ when(parent.getContextKeys(anyBoolean())).thenReturn(Collections.emptySet());
_preferenceStore = new BDBPreferenceStore(parent, _storeFile.getPath());
- _testInitialRecords = Arrays.<PreferenceRecord>asList(
- new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test")),
- new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test1")));
+ _testInitialRecords = Arrays.asList(
+ new PreferenceRecordImpl(UUID.randomUUID(), Collections.singletonMap("name", "test")),
+ new PreferenceRecordImpl(UUID.randomUUID(), Collections.singletonMap("name", "test1")));
populateTestData(_testInitialRecords, BrokerModel.MODEL_VERSION);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -114,7 +114,7 @@ public class BDBPreferenceStoreTest extends UnitTestBase
}
@Test
- public void testVersionAfterUpgrade() throws Exception
+ public void testVersionAfterUpgrade()
{
FileUtils.delete(_storeFile, true);
_storeFile.mkdirs();
@@ -126,18 +126,17 @@ public class BDBPreferenceStoreTest extends UnitTestBase
ModelVersion storedVersion = _preferenceStore.getStoredVersion();
- assertEquals("Unexpected version", BrokerModel.MODEL_VERSION, storedVersion.toString());
+ assertEquals(BrokerModel.MODEL_VERSION, storedVersion.toString(), "Unexpected version");
}
@Test
- public void testOpenAndLoad() throws Exception
+ public void testOpenAndLoad()
{
Collection<PreferenceRecord> recovered = _preferenceStore.openAndLoad(_updater);
- assertEquals("Unexpected store state",
- AbstractBDBPreferenceStore.StoreState.OPENED,
- _preferenceStore.getStoreState());
+ assertEquals(AbstractBDBPreferenceStore.StoreState.OPENED, _preferenceStore.getStoreState(),
+ "Unexpected store state");
- assertNotNull("Store was not properly opened", _preferenceStore.getEnvironmentFacade());
+ assertNotNull(_preferenceStore.getEnvironmentFacade(), "Store was not properly opened");
PreferenceTestHelper.assertRecords(_testInitialRecords, recovered);
}
@@ -146,22 +145,21 @@ public class BDBPreferenceStoreTest extends UnitTestBase
{
_preferenceStore.openAndLoad(_updater);
_preferenceStore.close();
- assertEquals("Unexpected store state",
- AbstractBDBPreferenceStore.StoreState.CLOSED,
- _preferenceStore.getStoreState());
- assertNull("Store was not properly closed", _preferenceStore.getEnvironmentFacade());
+ assertEquals(AbstractBDBPreferenceStore.StoreState.CLOSED, _preferenceStore.getStoreState(),
+ "Unexpected store state");
+ assertNull(_preferenceStore.getEnvironmentFacade(), "Store was not properly closed");
}
@Test
- public void testUpdateOrCreate() throws Exception
+ public void testUpdateOrCreate()
{
_preferenceStore.openAndLoad(_updater);
PreferenceRecord oldRecord = _testInitialRecords.get(0);
- Collection<PreferenceRecord> records = Arrays.<PreferenceRecord>asList(
- new PreferenceRecordImpl(oldRecord.getId(), Collections.<String, Object>singletonMap("name", "test2")),
- new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test3")));
+ Collection<PreferenceRecord> records = Arrays.asList(
+ new PreferenceRecordImpl(oldRecord.getId(), Collections.singletonMap("name", "test2")),
+ new PreferenceRecordImpl(UUID.randomUUID(), Collections.singletonMap("name", "test3")));
_preferenceStore.updateOrCreate(records);
_preferenceStore.close();
@@ -172,7 +170,7 @@ public class BDBPreferenceStoreTest extends UnitTestBase
}
@Test
- public void testReplace() throws Exception
+ public void testReplace()
{
_preferenceStore.openAndLoad(_updater);
@@ -180,9 +178,9 @@ public class BDBPreferenceStoreTest extends UnitTestBase
PreferenceRecord oldRecord2 = _testInitialRecords.get(1);
Collection<UUID> recordsToRemove = Collections.singleton(oldRecord1.getId());
- Collection<PreferenceRecord> recordsToAddUpdate = Arrays.<PreferenceRecord>asList(
- new PreferenceRecordImpl(oldRecord2.getId(), Collections.<String, Object>singletonMap("name", "test2")),
- new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test3")));
+ Collection<PreferenceRecord> recordsToAddUpdate = Arrays.asList(
+ new PreferenceRecordImpl(oldRecord2.getId(), Collections.singletonMap("name", "test2")),
+ new PreferenceRecordImpl(UUID.randomUUID(), Collections.singletonMap("name", "test3")));
_preferenceStore.replace(recordsToRemove, recordsToAddUpdate);
_preferenceStore.close();
@@ -191,11 +189,11 @@ public class BDBPreferenceStoreTest extends UnitTestBase
}
@Test
- public void testUpdateFailIfNotOpened() throws Exception
+ public void testUpdateFailIfNotOpened()
{
try
{
- _preferenceStore.updateOrCreate(Collections.<PreferenceRecord>emptyList());
+ _preferenceStore.updateOrCreate(Collections.emptyList());
fail("Should not be able to update or create");
}
catch (IllegalStateException e)
@@ -205,11 +203,11 @@ public class BDBPreferenceStoreTest extends UnitTestBase
}
@Test
- public void testReplaceFailIfNotOpened() throws Exception
+ public void testReplaceFailIfNotOpened()
{
try
{
- _preferenceStore.replace(Collections.<UUID>emptyList(), Collections.<PreferenceRecord>emptyList());
+ _preferenceStore.replace(Collections.<UUID>emptyList(), Collections.emptyList());
fail("Should not be able to replace");
}
catch (IllegalStateException e)
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
index b623cd6e00..477f6ca7ac 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgradeTestPreparer.java
@@ -25,7 +25,22 @@ import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
-import javax.jms.*;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.Topic;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.TopicPublisher;
+import javax.jms.TopicSession;
+import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
@@ -161,7 +176,7 @@ public class BDBStoreUpgradeTestPreparer
for (int msg = 0; msg < 5; msg++)
{
priorityQueueProducer.setPriority(msg % 10);
- Message message = session.createTextMessage(generateString(256*1024));
+ Message message = session.createTextMessage(generateString(256 * 1024));
message.setIntProperty("ID", msg);
priorityQueueProducer.send(message);
}
@@ -265,7 +280,7 @@ public class BDBStoreUpgradeTestPreparer
Topic topic = session.createTopic(SELECTOR_TOPIC_NAME);
// Create and register a durable subscriber with selector and then close it
- TopicSubscriber durSub1 = session.createDurableSubscriber(topic, SELECTOR_SUB_NAME,"testprop='true'", false);
+ TopicSubscriber durSub1 = session.createDurableSubscriber(topic, SELECTOR_SUB_NAME, "testprop='true'", false);
durSub1.close();
// Create a publisher and send a persistent message which matches the selector
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/CoalescingCommitterTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/CoalescingCommitterTest.java
index f7968b88e0..a79cbbea5b 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/CoalescingCommitterTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/CoalescingCommitterTest.java
@@ -20,24 +20,24 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.ListenableFuture;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.test.utils.UnitTestBase;
import org.apache.qpid.test.utils.VirtualHostNodeStoreType;
@@ -47,17 +47,18 @@ public class CoalescingCommitterTest extends UnitTestBase
private EnvironmentFacade _environmentFacade;
private CoalescingCommiter _coalescingCommitter;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_environmentFacade = mock(EnvironmentFacade.class);
_coalescingCommitter = new CoalescingCommiter("Test", 8, 500, _environmentFacade);
_coalescingCommitter.start();
}
- @After
+ @AfterEach
public void tearDown()
{
if (_coalescingCommitter != null)
@@ -67,7 +68,7 @@ public class CoalescingCommitterTest extends UnitTestBase
}
@Test
- public void testCommitterEnvironmentFacadeInteractionsOnSyncCommit() throws Exception
+ public void testCommitterEnvironmentFacadeInteractionsOnSyncCommit()
{
RuntimeException testFailure = new RuntimeException("Test");
doThrow(testFailure).when(_environmentFacade).flushLog();
@@ -79,7 +80,7 @@ public class CoalescingCommitterTest extends UnitTestBase
}
catch(RuntimeException e)
{
- assertEquals("Unexpected failure", testFailure, e);
+ assertEquals(testFailure, e, "Unexpected failure");
}
verify(_environmentFacade, times(1)).flushLog();
@@ -105,7 +106,7 @@ public class CoalescingCommitterTest extends UnitTestBase
}
catch (ExecutionException e)
{
- assertEquals("Unexpected failure", testFailure, e.getCause());
+ assertEquals(testFailure, e.getCause(), "Unexpected failure");
}
verify(_environmentFacade, times(1)).flushLog();
@@ -114,7 +115,7 @@ public class CoalescingCommitterTest extends UnitTestBase
final String expectedResult = "Test";
ListenableFuture<?> future = _coalescingCommitter.commitAsync(null, expectedResult);
Object result = future.get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Unexpected result", expectedResult, result);
+ assertEquals(expectedResult, result, "Unexpected result");
verify(_environmentFacade, times(2)).flushLog();
verify(_environmentFacade, times(1)).flushLogFailed(testFailure);
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/EnvHomeRegistryTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/EnvHomeRegistryTest.java
index 2bc2f27687..4c7f8a3ff2 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/EnvHomeRegistryTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/EnvHomeRegistryTest.java
@@ -19,21 +19,20 @@
package org.apache.qpid.server.store.berkeleydb;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.test.utils.UnitTestBase;
public class EnvHomeRegistryTest extends UnitTestBase
{
-
private final EnvHomeRegistry _ehr = new EnvHomeRegistry();
@Test
- public void testDuplicateEnvHomeRejected() throws Exception
+ public void testDuplicateEnvHomeRejected()
{
File home = new File(UnitTestBase.TMP_FOLDER, getTestName());
@@ -50,7 +49,7 @@ public class EnvHomeRegistryTest extends UnitTestBase
}
@Test
- public void testUniqueEnvHomesAllowed() throws Exception
+ public void testUniqueEnvHomesAllowed()
{
File home1 = new File(UnitTestBase.TMP_FOLDER, getTestName() + "1");
File home2 = new File(UnitTestBase.TMP_FOLDER, getTestName() + "2");
@@ -60,7 +59,7 @@ public class EnvHomeRegistryTest extends UnitTestBase
}
@Test
- public void testReuseOfEnvHomesAllowed() throws Exception
+ public void testReuseOfEnvHomesAllowed()
{
File home = new File(UnitTestBase.TMP_FOLDER, getTestName() + "1");
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeFactoryTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeFactoryTest.java
index 78a1543c41..c0927a700d 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeFactoryTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeFactoryTest.java
@@ -20,10 +20,8 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -31,12 +29,11 @@ import static org.mockito.Mockito.withSettings;
import java.io.File;
import java.util.Collections;
+import java.util.Objects;
import com.sleepycat.je.EnvironmentConfig;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.ConfiguredObject;
import org.apache.qpid.server.store.FileBasedSettings;
@@ -50,26 +47,24 @@ public class StandardEnvironmentFacadeFactoryTest extends UnitTestBase
private File _path;
private ConfiguredObject<?> _parent;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_path = TestFileUtils.createTestDirectory(".je.test", true);
// make mock object implementing FileBasedSettings
- _parent = mock(ConfiguredObject.class, withSettings().extraInterfaces(FileBasedSettings.class).defaultAnswer(new Answer()
- {
- @Override
- public Object answer(InvocationOnMock invocation)
- {
- if (invocation.getMethod().getName().equals("getStorePath"))
+ _parent = mock(ConfiguredObject.class, withSettings().extraInterfaces(FileBasedSettings.class)
+ .defaultAnswer(invocation ->
{
- return _path.getAbsolutePath();
- }
- return null;
- }
- }));
+ if (invocation.getMethod().getName().equals("getStorePath"))
+ {
+ return _path.getAbsolutePath();
+ }
+ return null;
+ }));
}
public void tearDown()throws Exception
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeTest.java
index 1a8db6c15f..2581d2b944 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacadeTest.java
@@ -27,13 +27,11 @@ import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.DEFAU
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.DEFAULT_QPID_BROKER_BDB_COMMITER_WAIT_TIMEOUT;
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.QPID_BROKER_BDB_COMMITER_NOTIFY_THRESHOLD;
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.QPID_BROKER_BDB_COMMITER_WAIT_TIMEOUT;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
@@ -44,14 +42,16 @@ import static org.mockito.Mockito.when;
import java.io.File;
import java.util.Collections;
import java.util.Map;
+import java.util.Objects;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Transaction;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.util.FileUtils;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -62,15 +62,16 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
protected File _storePath;
protected EnvironmentFacade _environmentFacade;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_storePath = new File(TMP_FOLDER + File.separator + "bdb" + File.separator + getTestName());
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -90,10 +91,10 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
}
@Test
- public void testSecondEnvironmentFacadeUsingSamePathRejected() throws Exception
+ public void testSecondEnvironmentFacadeUsingSamePathRejected()
{
EnvironmentFacade ef = createEnvironmentFacade();
- assertNotNull("Environment should not be null", ef);
+ assertNotNull(ef, "Environment should not be null");
try
{
createEnvironmentFacade();
@@ -107,7 +108,7 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
ef.close();
EnvironmentFacade ef2 = createEnvironmentFacade();
- assertNotNull("Environment should not be null", ef2);
+ assertNotNull(ef2, "Environment should not be null");
}
@Test
@@ -118,7 +119,7 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
}
@Test
- public void testOverrideJeParameter() throws Exception
+ public void testOverrideJeParameter()
{
// verify that transactions can be created by default
EnvironmentFacade ef = createEnvironmentFacade();
@@ -142,7 +143,7 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
@Test
- public void testOpenDatabaseReusesCachedHandle() throws Exception
+ public void testOpenDatabaseReusesCachedHandle()
{
DatabaseConfig createIfAbsentDbConfig = DatabaseConfig.DEFAULT.setAllowCreate(true);
@@ -151,17 +152,17 @@ public class StandardEnvironmentFacadeTest extends UnitTestBase
assertNotNull(handle1);
Database handle2 = ef.openDatabase("myDatabase", createIfAbsentDbConfig);
- assertSame("Database handle should be cached", handle1, handle2);
+ assertSame(handle1, handle2, "Database handle should be cached");
ef.closeDatabase("myDatabase");
Database handle3 = ef.openDatabase("myDatabase", createIfAbsentDbConfig);
- assertNotSame("Expecting a new handle after database closure", handle1, handle3);
+ assertNotSame(handle1, handle3, "Expecting a new handle after database closure");
}
EnvironmentFacade createEnvironmentFacade()
{
- _environmentFacade = createEnvironmentFacade(Collections.<String, String>emptyMap());
+ _environmentFacade = createEnvironmentFacade(Collections.emptyMap());
return _environmentFacade;
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacadeTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacadeTest.java
index e9c2acbcf5..755d3f3dec 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacadeTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacadeTest.java
@@ -27,16 +27,14 @@ import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.DEFAU
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.DEFAULT_QPID_BROKER_BDB_COMMITER_WAIT_TIMEOUT;
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.QPID_BROKER_BDB_COMMITER_NOTIFY_THRESHOLD;
import static org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost.QPID_BROKER_BDB_COMMITER_WAIT_TIMEOUT;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -53,8 +51,8 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
-import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@@ -65,7 +63,9 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import com.google.common.util.concurrent.SettableFuture;
+
import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.je.Database;
@@ -84,11 +84,12 @@ import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.ReplicatedEnvironment.State;
import com.sleepycat.je.rep.ReplicationConfig;
import com.sleepycat.je.rep.ReplicationNode;
-import com.sleepycat.je.rep.StateChangeEvent;
import com.sleepycat.je.rep.StateChangeListener;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -114,19 +115,23 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
private final boolean TEST_DESIGNATED_PRIMARY = false;
private final int TEST_PRIORITY = 1;
private final int TEST_ELECTABLE_GROUP_OVERRIDE = 0;
- private final Map<String, ReplicatedEnvironmentFacade> _nodes = new HashMap<String, ReplicatedEnvironmentFacade>();
- private final CopyOnWriteArrayList<Throwable> _unhandledExceptions = new CopyOnWriteArrayList<>();
private int _timeout = 30;
private File _storePath;
+ private Map<String, ReplicatedEnvironmentFacade> _nodes;
private Thread.UncaughtExceptionHandler _defaultUncaughtExceptionHandler;
+ private CopyOnWriteArrayList<Throwable> _unhandledExceptions;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_timeout = Integer.getInteger("ReplicatedEnvironmentFacadeTest.timeout", 30);
+ _nodes = new HashMap<>();
+ _unhandledExceptions = new CopyOnWriteArrayList<>();
+
_defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler((t, e) ->
{
@@ -138,14 +143,17 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
setTestSystemProperty(DB_PING_SOCKET_TIMEOUT_PROPERTY_NAME, "100");
}
- @After
- public void tearDown() throws Exception
+ @AfterEach
+ public void tearDown()
{
try
{
- for (EnvironmentFacade ef : _nodes.values())
+ if (_nodes != null)
{
- ef.close();
+ for (final EnvironmentFacade ef : _nodes.values())
+ {
+ ef.close();
+ }
}
}
finally
@@ -164,7 +172,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
}
finally
{
- if (!_unhandledExceptions.isEmpty())
+ if (_unhandledExceptions != null && !_unhandledExceptions.isEmpty())
{
fail("Unhandled exception(s) detected:" + _unhandledExceptions);
}
@@ -179,9 +187,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
ReplicatedEnvironmentFacade ef = createMaster();
ef.close();
- assertEquals("Unexpected state after close",
- ReplicatedEnvironmentFacade.State.CLOSED,
- ef.getFacadeState());
+ assertEquals(ReplicatedEnvironmentFacade.State.CLOSED, ef.getFacadeState(), "Unexpected state after close");
}
@@ -195,12 +201,12 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
assertNotNull(handle1);
Database handle2 = ef.openDatabase("myDatabase", createIfAbsentDbConfig);
- assertSame("Database handle should be cached", handle1, handle2);
+ assertSame(handle1, handle2, "Database handle should be cached");
ef.closeDatabase("myDatabase");
Database handle3 = ef.openDatabase("myDatabase", createIfAbsentDbConfig);
- assertNotSame("Expecting a new handle after database closure", handle1, handle3);
+ assertNotSame(handle1, handle3, "Expecting a new handle after database closure");
}
@Test
@@ -218,20 +224,20 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
}
catch(ConnectionScopedRuntimeException e)
{
- assertEquals("Unexpected exception", "Environment facade is not in opened state", e.getMessage());
+ assertEquals("Environment facade is not in opened state", e.getMessage(), "Unexpected exception");
}
}
@Test
public void testGetGroupName() throws Exception
{
- assertEquals("Unexpected group name", TEST_GROUP_NAME, createMaster().getGroupName());
+ assertEquals(TEST_GROUP_NAME, createMaster().getGroupName(), "Unexpected group name");
}
@Test
public void testGetNodeName() throws Exception
{
- assertEquals("Unexpected group name", TEST_NODE_NAME, createMaster().getNodeName());
+ assertEquals(TEST_NODE_NAME, createMaster().getNodeName(), "Unexpected group name");
}
@Test
@@ -239,67 +245,63 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
ReplicatedEnvironmentFacade master = createMaster();
long lastKnownReplicationTransactionId = master.getLastKnownReplicationTransactionId();
- assertTrue("Unexpected LastKnownReplicationTransactionId " + lastKnownReplicationTransactionId,
- lastKnownReplicationTransactionId > 0);
+ assertTrue(lastKnownReplicationTransactionId > 0,
+ "Unexpected LastKnownReplicationTransactionId " + lastKnownReplicationTransactionId);
}
@Test
public void testGetNodeHostPort() throws Exception
{
- assertEquals("Unexpected node host port", TEST_NODE_HOST_PORT, createMaster().getHostPort());
+ assertEquals(TEST_NODE_HOST_PORT, createMaster().getHostPort(), "Unexpected node host port");
}
@Test
public void testGetHelperHostPort() throws Exception
{
- assertEquals("Unexpected node helper host port",
- TEST_NODE_HELPER_HOST_PORT,
- createMaster().getHelperHostPort());
+ assertEquals(TEST_NODE_HELPER_HOST_PORT, createMaster().getHelperHostPort(),
+ "Unexpected node helper host port");
}
@Test
public void testSetMessageStoreDurability() throws Exception
{
ReplicatedEnvironmentFacade master = createMaster();
- assertEquals("Unexpected message store durability",
- new Durability(Durability.SyncPolicy.NO_SYNC, Durability.SyncPolicy.NO_SYNC, Durability.ReplicaAckPolicy.SIMPLE_MAJORITY),
- master.getRealMessageStoreDurability());
- assertEquals("Unexpected durability", TEST_DURABILITY, master.getMessageStoreDurability());
- assertTrue("Unexpected coalescing sync", master.isCoalescingSync());
+ assertEquals(new Durability(Durability.SyncPolicy.NO_SYNC, Durability.SyncPolicy.NO_SYNC,
+ Durability.ReplicaAckPolicy.SIMPLE_MAJORITY),
+ master.getRealMessageStoreDurability(), "Unexpected message store durability");
+ assertEquals(TEST_DURABILITY, master.getMessageStoreDurability(), "Unexpected durability");
+ assertTrue(master.isCoalescingSync(), "Unexpected coalescing sync");
master.setMessageStoreDurability(Durability.SyncPolicy.WRITE_NO_SYNC, Durability.SyncPolicy.SYNC, Durability.ReplicaAckPolicy.ALL);
- assertEquals("Unexpected message store durability",
- new Durability(Durability.SyncPolicy.WRITE_NO_SYNC, Durability.SyncPolicy.SYNC, Durability.ReplicaAckPolicy.ALL),
- master.getRealMessageStoreDurability());
- assertFalse("Coalescing sync committer is still running", master.isCoalescingSync());
+ assertEquals(new Durability(Durability.SyncPolicy.WRITE_NO_SYNC, Durability.SyncPolicy.SYNC,
+ Durability.ReplicaAckPolicy.ALL),
+ master.getRealMessageStoreDurability(), "Unexpected message store durability");
+ assertFalse(master.isCoalescingSync(), "Coalescing sync committer is still running");
}
@Test
public void testSetMessageStoreDurabilityWithDisabledCoalescingSync() throws Exception
{
ReplicatedEnvironmentFacade master = createMaster(true);
- assertEquals("Unexpected message store durability",
- new Durability(Durability.SyncPolicy.NO_SYNC, Durability.SyncPolicy.NO_SYNC,
- Durability.ReplicaAckPolicy.SIMPLE_MAJORITY),
- master.getRealMessageStoreDurability());
- assertTrue("Unexpected coalescing sync", master.isCoalescingSync());
+ assertEquals(new Durability(Durability.SyncPolicy.NO_SYNC, Durability.SyncPolicy.NO_SYNC,
+ Durability.ReplicaAckPolicy.SIMPLE_MAJORITY),
+ master.getRealMessageStoreDurability(), "Unexpected message store durability");
+ assertTrue(master.isCoalescingSync(), "Unexpected coalescing sync");
master.setMessageStoreDurability(Durability.SyncPolicy.NO_SYNC,
Durability.SyncPolicy.WRITE_NO_SYNC,
Durability.ReplicaAckPolicy.ALL);
- assertEquals("Unexpected message store durability",
- new Durability(Durability.SyncPolicy.NO_SYNC,
- Durability.SyncPolicy.WRITE_NO_SYNC,
- Durability.ReplicaAckPolicy.ALL),
- master.getRealMessageStoreDurability());
- assertFalse("Coalescing sync committer is still running", master.isCoalescingSync());
+ assertEquals(new Durability(Durability.SyncPolicy.NO_SYNC, Durability.SyncPolicy.WRITE_NO_SYNC,
+ Durability.ReplicaAckPolicy.ALL),
+ master.getRealMessageStoreDurability(), "Unexpected message store durability");
+ assertFalse(master.isCoalescingSync(), "Coalescing sync committer is still running");
}
@Test
public void testGetNodeState() throws Exception
{
- assertEquals("Unexpected state", State.MASTER.name(), createMaster().getNodeState());
+ assertEquals(State.MASTER.name(), createMaster().getNodeState(), "Unexpected state");
}
@Test
@@ -310,17 +312,17 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentConfiguration masterConfig = createReplicatedEnvironmentConfiguration(TEST_NODE_NAME, TEST_NODE_HOST_PORT, TEST_DESIGNATED_PRIMARY);
ReplicatedEnvironmentFacade facade = createReplicatedEnvironmentFacade(TEST_NODE_NAME, masterListener, masterGroupListener, masterConfig);
- assertTrue("Master was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not created");
- assertEquals("Unexpected priority", (long) TEST_PRIORITY, (long) facade.getPriority());
+ assertEquals(TEST_PRIORITY, (long) facade.getPriority(), "Unexpected priority");
int newPriority = TEST_PRIORITY + 1;
when(masterConfig.getPriority()).thenReturn(newPriority);
Future<Void> future = facade.reapplyPriority();
future.get(_timeout, TimeUnit.SECONDS);
- assertEquals("Unexpected priority after change", (long) newPriority, (long) facade.getPriority());
+ assertEquals(newPriority, (long) facade.getPriority(), "Unexpected priority after change");
}
@Test
@@ -331,17 +333,16 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentConfiguration masterConfig = createReplicatedEnvironmentConfiguration(TEST_NODE_NAME, TEST_NODE_HOST_PORT, TEST_DESIGNATED_PRIMARY);
ReplicatedEnvironmentFacade master = createReplicatedEnvironmentFacade(TEST_NODE_NAME, masterListener, masterGroupListener, masterConfig);
- assertTrue("Master was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not created");
- assertEquals("Unexpected designated primary", TEST_DESIGNATED_PRIMARY, master.isDesignatedPrimary());
+ assertEquals(TEST_DESIGNATED_PRIMARY, master.isDesignatedPrimary(), "Unexpected designated primary");
boolean newDesignatedPrimary = !TEST_DESIGNATED_PRIMARY;
when(masterConfig.isDesignatedPrimary()).thenReturn(newDesignatedPrimary);
Future<Void> future = master.reapplyDesignatedPrimary();
future.get(_timeout, TimeUnit.SECONDS);
- assertEquals("Unexpected designated primary after change",
- newDesignatedPrimary,
- master.isDesignatedPrimary());
+ assertEquals(newDesignatedPrimary, master.isDesignatedPrimary(),
+ "Unexpected designated primary after change");
}
@Test
@@ -352,12 +353,11 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentConfiguration masterConfig = createReplicatedEnvironmentConfiguration(TEST_NODE_NAME, TEST_NODE_HOST_PORT, false);
ReplicatedEnvironmentFacade facade = createReplicatedEnvironmentFacade(TEST_NODE_NAME, masterListener, masterGroupListener, masterConfig);
- assertTrue("Master was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not created");
- assertEquals("Unexpected Electable Group Size Override",
- (long) TEST_ELECTABLE_GROUP_OVERRIDE,
- (long) facade.getElectableGroupSizeOverride());
+ assertEquals(TEST_ELECTABLE_GROUP_OVERRIDE, (long) facade.getElectableGroupSizeOverride(),
+ "Unexpected Electable Group Size Override");
int newElectableGroupOverride = TEST_ELECTABLE_GROUP_OVERRIDE + 1;
@@ -365,9 +365,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
Future<Void> future = facade.reapplyElectableGroupSizeOverride();
future.get(_timeout, TimeUnit.SECONDS);
- assertEquals("Unexpected Electable Group Size Override after change",
- (long) newElectableGroupOverride,
- (long) facade.getElectableGroupSizeOverride());
+ assertEquals(newElectableGroupOverride, (long) facade.getElectableGroupSizeOverride(),
+ "Unexpected Electable Group Size Override after change");
}
@Test
@@ -393,10 +392,10 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
createReplica(nodeName2, node2NodeHostPort, listener);
- assertEquals("Unexpected number of nodes", (long) 2, (long) master.getNumberOfElectableGroupMembers());
+ assertEquals(2, (long) master.getNumberOfElectableGroupMembers(), "Unexpected number of nodes");
- assertTrue("Listener not fired within timeout", nodeRecoveryLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected number of listener invocations", (long) 1, (long) invocationCount.get());
+ assertTrue(nodeRecoveryLatch.await(_timeout, TimeUnit.SECONDS), "Listener not fired within timeout");
+ assertEquals(1, (long) invocationCount.get(), "Unexpected number of listener invocations");
}
@Test
@@ -416,26 +415,22 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener stateChangeListener = new TestStateChangeListener();
ReplicatedEnvironmentFacade replicatedEnvironmentFacade = addNode(stateChangeListener, listener);
- assertTrue("Master was not started", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit
- .SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not started");
- assertEquals("Unexpected number of nodes at start of test",
- (long) 1,
- (long) replicatedEnvironmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(1, replicatedEnvironmentFacade.getNumberOfElectableGroupMembers(),
+ "Unexpected number of nodes at start of test");
String node2Name = TEST_NODE_NAME + "_2";
String node2NodeHostPort = "localhost" + ":" + _portHelper.getNextAvailable();
replicatedEnvironmentFacade.setPermittedNodes(Arrays.asList(replicatedEnvironmentFacade.getHostPort(), node2NodeHostPort));
createReplica(node2Name, node2NodeHostPort, new NoopReplicationGroupListener());
- assertTrue("Listener not fired within timeout", nodeAddedLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(nodeAddedLatch.await(_timeout, TimeUnit.SECONDS), "Listener not fired within timeout");
- assertEquals("Unexpected number of nodes",
- (long) 2,
- (long) replicatedEnvironmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(2, replicatedEnvironmentFacade.getNumberOfElectableGroupMembers(), "Unexpected number of nodes");
- assertEquals("Unexpected number of listener invocations", (long) 1, (long) invocationCount.get());
+ assertEquals(1, invocationCount.get(), "Unexpected number of listener invocations");
}
@Test
@@ -470,31 +465,29 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentFacade replicatedEnvironmentFacade = addNode(stateChangeListener, listener);
// Set the node to be primary so that the node will remain master even when the 2nd node is shutdown
replicatedEnvironmentFacade.reapplyDesignatedPrimary();
- assertTrue("Master was not started", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not started");
String node2Name = TEST_NODE_NAME + "_2";
String node2NodeHostPort = "localhost" + ":" + _portHelper.getNextAvailable();
replicatedEnvironmentFacade.setPermittedNodes(Arrays.asList(replicatedEnvironmentFacade.getHostPort(), node2NodeHostPort));
createReplica(node2Name, node2NodeHostPort, new NoopReplicationGroupListener());
- assertEquals("Unexpected number of nodes at start of test",
- (long) 2,
- (long) replicatedEnvironmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(2, replicatedEnvironmentFacade.getNumberOfElectableGroupMembers(),
+ "Unexpected number of nodes at start of test");
// Need to await the listener hearing the addition of the node to the model.
- assertTrue("Node add not fired within timeout", nodeAddedLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(nodeAddedLatch.await(_timeout, TimeUnit.SECONDS), "Node add not fired within timeout");
// Now remove the node and ensure we hear the event
replicatedEnvironmentFacade.removeNodeFromGroup(node2Name);
- assertTrue("Node delete not fired within timeout", nodeDeletedLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(nodeDeletedLatch.await(_timeout, TimeUnit.SECONDS), "Node delete not fired within timeout");
- assertEquals("Unexpected number of nodes after node removal",
- (long) 1,
- (long) replicatedEnvironmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(1, replicatedEnvironmentFacade.getNumberOfElectableGroupMembers(),
+ "Unexpected number of nodes after node removal");
- assertEquals("Unexpected number of listener invocations", (long) 1, (long) invocationCount.get());
+ assertEquals(1, invocationCount.get(), "Unexpected number of listener invocations");
}
@Test
@@ -502,9 +495,9 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
final String node2Name = TEST_NODE_NAME + "_2";
final CountDownLatch nodeAddedLatch = new CountDownLatch(1);
- final AtomicReference<ReplicationNode> nodeRef = new AtomicReference<ReplicationNode>();
+ final AtomicReference<ReplicationNode> nodeRef = new AtomicReference<>();
final CountDownLatch stateLatch = new CountDownLatch(1);
- final AtomicReference<NodeState> stateRef = new AtomicReference<NodeState>();
+ final AtomicReference<NodeState> stateRef = new AtomicReference<>();
ReplicationGroupListener listener = new NoopReplicationGroupListener()
{
@Override
@@ -527,25 +520,23 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener stateChangeListener = new TestStateChangeListener();
ReplicatedEnvironmentFacade replicatedEnvironmentFacade = addNode(stateChangeListener, listener);
- assertTrue("Master was not started", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit
- .SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not started");
String node2NodeHostPort = "localhost" + ":" + _portHelper.getNextAvailable();
replicatedEnvironmentFacade.setPermittedNodes(Arrays.asList(replicatedEnvironmentFacade.getHostPort(), node2NodeHostPort));
createReplica(node2Name, node2NodeHostPort, new NoopReplicationGroupListener());
- assertEquals("Unexpected number of nodes at start of test",
- (long) 2,
- (long) replicatedEnvironmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(2, replicatedEnvironmentFacade.getNumberOfElectableGroupMembers(),
+ "Unexpected number of nodes at start of test");
- assertTrue("Node add not fired within timeout", nodeAddedLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(nodeAddedLatch.await(_timeout, TimeUnit.SECONDS), "Node add not fired within timeout");
- ReplicationNode remoteNode = (ReplicationNode)nodeRef.get();
- assertEquals("Unexpected node name", node2Name, remoteNode.getName());
+ ReplicationNode remoteNode = nodeRef.get();
+ assertEquals(node2Name, remoteNode.getName(), "Unexpected node name");
- assertTrue("Node state not fired within timeout", stateLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected node state", State.REPLICA, stateRef.get().getNodeState());
+ assertTrue(stateLatch.await(_timeout, TimeUnit.SECONDS), "Node state not fired within timeout");
+ assertEquals(State.REPLICA, stateRef.get().getNodeState(), "Unexpected node state");
}
@Test
@@ -554,23 +545,18 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener stateChangeListener = new TestStateChangeListener();
ReplicatedEnvironmentFacade environmentFacade = addNode(TEST_NODE_NAME, TEST_NODE_HOST_PORT, true, stateChangeListener,
new NoopReplicationGroupListener());
- assertTrue("Environment was not created", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Environment was not created");
String node2Name = TEST_NODE_NAME + "_2";
String node2NodeHostPort = "localhost:" + _portHelper.getNextAvailable();
- ReplicatedEnvironmentFacade ref2 = createReplica(node2Name, node2NodeHostPort,
- new NoopReplicationGroupListener());
+ ReplicatedEnvironmentFacade ref2 = createReplica(node2Name, node2NodeHostPort, new NoopReplicationGroupListener());
- assertEquals("Unexpected group members count",
- (long) 2,
- (long) environmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(2, environmentFacade.getNumberOfElectableGroupMembers(), "Unexpected group members count");
ref2.close();
environmentFacade.removeNodeFromGroup(node2Name);
- assertEquals("Unexpected group members count",
- (long) 1,
- (long) environmentFacade.getNumberOfElectableGroupMembers());
+ assertEquals(1, environmentFacade.getNumberOfElectableGroupMembers(), "Unexpected group members count");
}
@Test
@@ -582,8 +568,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
true,
stateChangeListener,
new NoopReplicationGroupListener());
- assertTrue("Environment was not created", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Environment was not created");
String node2Name = TEST_NODE_NAME + "_2";
String node2NodeHostPort = "localhost:" + _portHelper.getNextAvailable();
@@ -609,10 +595,10 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
final String replicaName = TEST_NODE_NAME + "_1";
final CountDownLatch nodeRemovedLatch = new CountDownLatch(1);
final CountDownLatch nodeAddedLatch = new CountDownLatch(1);
- final AtomicReference<ReplicationNode> addedNodeRef = new AtomicReference<ReplicationNode>();
- final AtomicReference<ReplicationNode> removedNodeRef = new AtomicReference<ReplicationNode>();
+ final AtomicReference<ReplicationNode> addedNodeRef = new AtomicReference<>();
+ final AtomicReference<ReplicationNode> removedNodeRef = new AtomicReference<>();
final CountDownLatch stateLatch = new CountDownLatch(1);
- final AtomicReference<NodeState> stateRef = new AtomicReference<NodeState>();
+ final AtomicReference<NodeState> stateRef = new AtomicReference<>();
ReplicationGroupListener listener = new NoopReplicationGroupListener()
{
@@ -645,8 +631,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener stateChangeListener = new TestStateChangeListener();
final ReplicatedEnvironmentFacade masterEnvironment = addNode(stateChangeListener, listener);
- assertTrue("Master was not started", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not started");
masterEnvironment.reapplyDesignatedPrimary();
@@ -656,21 +642,21 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentFacade replica = createReplica(replicaName, node1NodeHostPort,
new NoopReplicationGroupListener());
- assertTrue("Node should be added", nodeAddedLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(nodeAddedLatch.await(_timeout, TimeUnit.SECONDS), "Node should be added");
ReplicationNode node = addedNodeRef.get();
- assertEquals("Unexpected node name", replicaName, node.getName());
+ assertEquals(replicaName, node.getName(), "Unexpected node name");
- assertTrue("Node state was not heard", stateLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected node role", State.REPLICA, stateRef.get().getNodeState());
- assertEquals("Unexpected node name", replicaName, stateRef.get().getNodeName());
+ assertTrue(stateLatch.await(_timeout, TimeUnit.SECONDS), "Node state was not heard");
+ assertEquals(State.REPLICA, stateRef.get().getNodeState(), "Unexpected node role");
+ assertEquals(replicaName, stateRef.get().getNodeName(), "Unexpected node name");
replica.close();
masterEnvironment.removeNodeFromGroup(node.getName());
- assertTrue("Node deleting is undetected by the environment facade",
- nodeRemovedLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected node is deleted", node, removedNodeRef.get());
+ assertTrue(nodeRemovedLatch.await(_timeout, TimeUnit.SECONDS),
+ "Node deleting is undetected by the environment facade");
+ assertEquals(node, removedNodeRef.get(), "Unexpected node is deleted");
}
@Test
@@ -678,13 +664,11 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
ReplicatedEnvironmentFacade replicatedEnvironmentFacade = createMaster();
- assertEquals("Unexpected state " + replicatedEnvironmentFacade.getFacadeState(),
- ReplicatedEnvironmentFacade.State.OPEN,
- replicatedEnvironmentFacade.getFacadeState());
+ assertEquals(ReplicatedEnvironmentFacade.State.OPEN, replicatedEnvironmentFacade.getFacadeState(),
+ "Unexpected state " + replicatedEnvironmentFacade.getFacadeState());
replicatedEnvironmentFacade.close();
- assertEquals("Unexpected state " + replicatedEnvironmentFacade.getFacadeState(),
- ReplicatedEnvironmentFacade.State.CLOSED,
- replicatedEnvironmentFacade.getFacadeState());
+ assertEquals(ReplicatedEnvironmentFacade.State.CLOSED, replicatedEnvironmentFacade.getFacadeState(),
+ "Unexpected state " + replicatedEnvironmentFacade.getFacadeState());
}
@Test
@@ -695,29 +679,25 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
final AtomicInteger masterStateChangeCount = new AtomicInteger();
final CountDownLatch unknownLatch = new CountDownLatch(1);
final AtomicInteger unknownStateChangeCount = new AtomicInteger();
- StateChangeListener stateChangeListener = new StateChangeListener()
+ StateChangeListener stateChangeListener = stateChangeEvent ->
{
- @Override
- public void stateChange(StateChangeEvent stateChangeEvent) throws RuntimeException
+ if (stateChangeEvent.getState() == State.MASTER)
{
- if (stateChangeEvent.getState() == State.MASTER)
+ masterStateChangeCount.incrementAndGet();
+ if (masterLatch.getCount() == 1)
{
- masterStateChangeCount.incrementAndGet();
- if (masterLatch.getCount() == 1)
- {
- masterLatch.countDown();
- }
- else
- {
- secondMasterLatch.countDown();
- }
+ masterLatch.countDown();
}
- else if (stateChangeEvent.getState() == State.UNKNOWN)
+ else
{
- unknownStateChangeCount.incrementAndGet();
- unknownLatch.countDown();
+ secondMasterLatch.countDown();
}
}
+ else if (stateChangeEvent.getState() == State.UNKNOWN)
+ {
+ unknownStateChangeCount.incrementAndGet();
+ unknownLatch.countDown();
+ }
};
// make sure that node is re-elected as MASTER on second start-up
@@ -726,7 +706,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
createReplicatedEnvironmentFacade(TEST_NODE_NAME, stateChangeListener,
new NoopReplicationGroupListener(), config);
- assertTrue("Master was not started", masterLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(masterLatch.await(_timeout, TimeUnit.SECONDS), "Master was not started");
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
@@ -742,20 +722,16 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
replica1.close();
replica2.close();
- assertTrue("Environment should be recreated and go into unknown state", unknownLatch.await(_timeout,
- TimeUnit.SECONDS));
+ assertTrue(unknownLatch.await(_timeout, TimeUnit.SECONDS),
+ "Environment should be recreated and go into unknown state");
// bring back the cluster in order to make sure that no extra state transition happens between UNKNOWN and MASTER
createReplica(TEST_NODE_NAME + "_1", node1NodeHostPort, new NoopReplicationGroupListener());
- assertTrue("Master node did not resume", secondMasterLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(secondMasterLatch.await(_timeout, TimeUnit.SECONDS), "Master node did not resume");
- assertEquals("Node transited into Master state unexpected number of times",
- (long) 2,
- (long) masterStateChangeCount.get());
- assertEquals("Node transited into Unknown state unexpected number of times",
- (long) 1,
- (long) unknownStateChangeCount.get());
+ assertEquals(2, masterStateChangeCount.get(), "Node transited into Master state unexpected number of times");
+ assertEquals(1, unknownStateChangeCount.get(), "Node transited into Unknown state unexpected number of times");
}
@Test
@@ -763,63 +739,54 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
final CountDownLatch firstNodeReplicaStateLatch = new CountDownLatch(1);
final CountDownLatch firstNodeMasterStateLatch = new CountDownLatch(1);
- StateChangeListener stateChangeListener = new StateChangeListener(){
-
- @Override
- public void stateChange(StateChangeEvent event) throws RuntimeException
+ StateChangeListener stateChangeListener = event ->
+ {
+ State state = event.getState();
+ if (state == State.REPLICA)
{
- ReplicatedEnvironment.State state = event.getState();
- if (state == ReplicatedEnvironment.State.REPLICA)
- {
- firstNodeReplicaStateLatch.countDown();
- }
- if (state == ReplicatedEnvironment.State.MASTER)
- {
- firstNodeMasterStateLatch.countDown();
- }
+ firstNodeReplicaStateLatch.countDown();
+ }
+ if (state == State.MASTER)
+ {
+ firstNodeMasterStateLatch.countDown();
}
};
ReplicatedEnvironmentFacade firstNode = addNode(stateChangeListener, new NoopReplicationGroupListener());
- assertTrue("Environment did not become a master",
- firstNodeMasterStateLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(firstNodeMasterStateLatch.await(_timeout, TimeUnit.SECONDS), "Environment did not become a master");
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
ReplicatedEnvironmentFacade secondNode = createReplica(TEST_NODE_NAME + "_1", node1NodeHostPort,
new NoopReplicationGroupListener());
- assertEquals("Unexpected state", State.REPLICA.name(), secondNode.getNodeState());
+ assertEquals(State.REPLICA.name(), secondNode.getNodeState(), "Unexpected state");
int replica2Port = _portHelper.getNextAvailable();
String node2NodeHostPort = "localhost:" + replica2Port;
final CountDownLatch replicaStateLatch = new CountDownLatch(1);
final CountDownLatch masterStateLatch = new CountDownLatch(1);
- StateChangeListener testStateChangeListener = new StateChangeListener()
+ StateChangeListener testStateChangeListener = event ->
{
- @Override
- public void stateChange(StateChangeEvent event) throws RuntimeException
+ State state = event.getState();
+ if (state == State.REPLICA)
{
- ReplicatedEnvironment.State state = event.getState();
- if (state == ReplicatedEnvironment.State.REPLICA)
- {
- replicaStateLatch.countDown();
- }
- if (state == ReplicatedEnvironment.State.MASTER)
- {
- masterStateLatch.countDown();
- }
+ replicaStateLatch.countDown();
+ }
+ if (state == State.MASTER)
+ {
+ masterStateLatch.countDown();
}
};
ReplicatedEnvironmentFacade thirdNode = addNode(TEST_NODE_NAME + "_2", node2NodeHostPort, TEST_DESIGNATED_PRIMARY,
testStateChangeListener,
new NoopReplicationGroupListener());
- assertTrue("Environment did not become a replica", replicaStateLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals((long) 3, (long) thirdNode.getNumberOfElectableGroupMembers());
+ assertTrue(replicaStateLatch.await(_timeout, TimeUnit.SECONDS), "Environment did not become a replica");
+ assertEquals(3, (long) thirdNode.getNumberOfElectableGroupMembers());
thirdNode.transferMasterToSelfAsynchronously();
- assertTrue("Environment did not become a master", masterStateLatch.await(_timeout, TimeUnit.SECONDS));
- assertTrue("First node environment did not become a replica", firstNodeReplicaStateLatch.await(
- _timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected state", State.REPLICA.name(), firstNode.getNodeState());
+ assertTrue(masterStateLatch.await(_timeout, TimeUnit.SECONDS), "Environment did not become a master");
+ assertTrue(firstNodeReplicaStateLatch.await(_timeout, TimeUnit.SECONDS),
+ "First node environment did not become a replica");
+ assertEquals(State.REPLICA.name(), firstNode.getNodeState(), "Unexpected state");
}
@Test
@@ -827,63 +794,55 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
final CountDownLatch firstNodeReplicaStateLatch = new CountDownLatch(1);
final CountDownLatch firstNodeMasterStateLatch = new CountDownLatch(1);
- StateChangeListener stateChangeListener = new StateChangeListener(){
-
- @Override
- public void stateChange(StateChangeEvent event) throws RuntimeException
+ StateChangeListener stateChangeListener = event ->
+ {
+ State state = event.getState();
+ if (state == State.REPLICA)
{
- ReplicatedEnvironment.State state = event.getState();
- if (state == ReplicatedEnvironment.State.REPLICA)
- {
- firstNodeReplicaStateLatch.countDown();
- }
- if (state == ReplicatedEnvironment.State.MASTER)
- {
- firstNodeMasterStateLatch.countDown();
- }
+ firstNodeReplicaStateLatch.countDown();
+ }
+ if (state == State.MASTER)
+ {
+ firstNodeMasterStateLatch.countDown();
}
};
ReplicatedEnvironmentFacade firstNode = addNode(stateChangeListener, new NoopReplicationGroupListener());
- assertTrue("Environment did not become a master",
- firstNodeMasterStateLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(firstNodeMasterStateLatch.await(_timeout, TimeUnit.SECONDS),
+ "Environment did not become a master");
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
ReplicatedEnvironmentFacade secondNode = createReplica(TEST_NODE_NAME + "_1", node1NodeHostPort,
new NoopReplicationGroupListener());
- assertEquals("Unexpected state", State.REPLICA.name(), secondNode.getNodeState());
+ assertEquals(State.REPLICA.name(), secondNode.getNodeState(), "Unexpected state");
int replica2Port = _portHelper.getNextAvailable();
String node2NodeHostPort = "localhost:" + replica2Port;
final CountDownLatch replicaStateLatch = new CountDownLatch(1);
final CountDownLatch masterStateLatch = new CountDownLatch(1);
- StateChangeListener testStateChangeListener = new StateChangeListener()
+ StateChangeListener testStateChangeListener = event ->
{
- @Override
- public void stateChange(StateChangeEvent event) throws RuntimeException
+ State state = event.getState();
+ if (state == State.REPLICA)
{
- ReplicatedEnvironment.State state = event.getState();
- if (state == ReplicatedEnvironment.State.REPLICA)
- {
- replicaStateLatch.countDown();
- }
- if (state == ReplicatedEnvironment.State.MASTER)
- {
- masterStateLatch.countDown();
- }
+ replicaStateLatch.countDown();
+ }
+ if (state == State.MASTER)
+ {
+ masterStateLatch.countDown();
}
};
String thirdNodeName = TEST_NODE_NAME + "_2";
ReplicatedEnvironmentFacade thirdNode = addNode(thirdNodeName, node2NodeHostPort, TEST_DESIGNATED_PRIMARY,
testStateChangeListener, new NoopReplicationGroupListener());
- assertTrue("Environment did not become a replica", replicaStateLatch.await(_timeout, TimeUnit.SECONDS));
- assertEquals((long) 3, (long) thirdNode.getNumberOfElectableGroupMembers());
+ assertTrue(replicaStateLatch.await(_timeout, TimeUnit.SECONDS), "Environment did not become a replica");
+ assertEquals(3, thirdNode.getNumberOfElectableGroupMembers());
firstNode.transferMasterAsynchronously(thirdNodeName);
- assertTrue("Environment did not become a master", masterStateLatch.await(_timeout, TimeUnit.SECONDS));
- assertTrue("First node environment did not become a replica", firstNodeReplicaStateLatch.await(
- _timeout, TimeUnit.SECONDS));
- assertEquals("Unexpected state", State.REPLICA.name(), firstNode.getNodeState());
+ assertTrue(masterStateLatch.await(_timeout, TimeUnit.SECONDS), "Environment did not become a master");
+ assertTrue(firstNodeReplicaStateLatch.await(_timeout, TimeUnit.SECONDS),
+ "First node environment did not become a replica");
+ assertEquals(State.REPLICA.name(), firstNode.getNodeState(), "Unexpected state");
}
@Test
@@ -896,7 +855,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TransactionConfig transactionConfig = new TransactionConfig();
transactionConfig.setDurability(facade.getRealMessageStoreDurability());
txn = facade.beginTransaction(transactionConfig);
- assertNotNull("Transaction is not created", txn);
+ assertNotNull(txn, "Transaction is not created");
txn.commit();
txn = null;
}
@@ -914,7 +873,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
ReplicatedEnvironmentFacade firstNode = createMaster();
- Set<String> permittedNodes = new HashSet<String>();
+ Set<String> permittedNodes = new HashSet<>();
permittedNodes.add("localhost:" + TEST_NODE_PORT);
permittedNodes.add("localhost:" + _portHelper.getNextAvailable());
firstNode.setPermittedNodes(permittedNodes);
@@ -926,7 +885,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
Map<String, Object> settings = objectMapper.readValue(nodeState.getAppState(), Map.class);
Collection<String> appStatePermittedNodes = (Collection<String>)settings.get(PERMITTED_NODE_LIST);
- assertEquals("Unexpected permitted nodes", permittedNodes, new HashSet<String>(appStatePermittedNodes));
+ assertEquals(permittedNodes, new HashSet<>(appStatePermittedNodes), "Unexpected permitted nodes");
}
@Test
@@ -937,7 +896,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
- Set<String> permittedNodes = new HashSet<String>();
+ Set<String> permittedNodes = new HashSet<>();
permittedNodes.add("localhost:" + TEST_NODE_PORT);
permittedNodes.add(node1NodeHostPort);
firstNode.setPermittedNodes(permittedNodes);
@@ -947,7 +906,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentFacade secondNode =
createNode(configuration, TEST_NODE_NAME + "_1", State.REPLICA);
- assertEquals("Unexpected state", State.REPLICA.name(), secondNode.getNodeState());
+ assertEquals(State.REPLICA.name(), secondNode.getNodeState(), "Unexpected state");
}
@Test
@@ -967,14 +926,14 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
- Set<String> permittedNodes = new HashSet<String>();
+ Set<String> permittedNodes = new HashSet<>();
permittedNodes.add("localhost:" + TEST_NODE_PORT);
firstNode.setPermittedNodes(permittedNodes);
String nodeName = TEST_NODE_NAME + "_1";
createIntruder(nodeName, node1NodeHostPort);
- assertTrue("Intruder node was not detected", intruderLatch.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(intruderLatch.await(_timeout, TimeUnit.SECONDS), "Intruder node was not detected");
}
@Test
@@ -985,8 +944,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener masterListener = new TestStateChangeListener();
ReplicatedEnvironmentFacade node1 = addNode(TEST_NODE_NAME, TEST_NODE_HOST_PORT, true, masterListener,
new NoopReplicationGroupListener());
- assertTrue("Environment was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Environment was not created");
String replicaNodeHostPort = "localhost:" + _portHelper.getNextAvailable();
String replicaName = TEST_NODE_NAME + 1;
@@ -1013,10 +972,9 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
TestStateChangeListener node2StateChangeListener = new TestStateChangeListener();
node2 = addNode(replicaName, replicaNodeHostPort, true, node2StateChangeListener,
new NoopReplicationGroupListener());
- boolean awaitForStateChange = node2StateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS);
- assertTrue(replicaName + " did not go into desired state; current actual state is "
- + node2StateChangeListener.getCurrentActualState(), awaitForStateChange);
+ boolean awaitForStateChange = node2StateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS);
+ assertTrue(awaitForStateChange, replicaName + " did not go into desired state; current actual state is " +
+ node2StateChangeListener.getCurrentActualState());
db = node2.openDatabase("mydb", DatabaseConfig.DEFAULT);
@@ -1036,10 +994,10 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
_replicaRolledback.countDown();
}
});
- assertTrue("Node 1 did not go into desired state", node1StateChangeListener.awaitForStateChange(State.REPLICA,
- _timeout, TimeUnit.SECONDS));
- assertTrue("Node 1 did not experience rollback within timeout",
- _replicaRolledback.await(_timeout, TimeUnit.SECONDS));
+ assertTrue(node1StateChangeListener.awaitForStateChange(State.REPLICA, _timeout, TimeUnit.SECONDS),
+ "Node 1 did not go into desired state");
+ assertTrue(_replicaRolledback.await(_timeout, TimeUnit.SECONDS),
+ "Node 1 did not experience rollback within timeout");
// Finally do one more transaction through the master
putRecord(node2, db, 4, "value4", false);
@@ -1071,16 +1029,9 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
try
{
- Future<Transaction> future = service.submit(new Callable<Transaction>(){
-
- @Override
- public Transaction call() throws Exception
- {
- return replica.beginTransaction(null);
- }
- });
+ Future<Transaction> future = service.submit(() -> replica.beginTransaction(null));
Transaction transaction = future.get(_timeout, TimeUnit.SECONDS);
- assertNotNull("Transaction was not created during expected time", transaction);
+ assertNotNull(transaction, "Transaction was not created during expected time");
transaction.abort();
}
finally
@@ -1113,7 +1064,7 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
RuntimeException handledException = master.handleDatabaseException("test", e);
final boolean condition = handledException instanceof ConnectionScopedRuntimeException;
- assertTrue("Unexpected exception", condition);
+ assertTrue(condition, "Unexpected exception");
}
}
@@ -1134,8 +1085,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentConfiguration masterConfig = createReplicatedEnvironmentConfiguration(TEST_NODE_NAME, TEST_NODE_HOST_PORT, false);
ReplicatedEnvironmentFacade master = createReplicatedEnvironmentFacade(TEST_NODE_NAME, masterListener, masterGroupListener, masterConfig);
- assertTrue("Master was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not created");
int replica1Port = _portHelper.getNextAvailable();
String node1NodeHostPort = "localhost:" + replica1Port;
@@ -1152,20 +1103,17 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
replica1.close();
replica2.close();
- assertTrue("Node that was master did not become detached after the replica closed",
- masterListener.awaitForStateChange(State.DETACHED, _timeout, TimeUnit.SECONDS));
- assertTrue("Majority lost is undetected", majorityLost.get(_timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.DETACHED, _timeout, TimeUnit.SECONDS),
+ "Node that was master did not become detached after the replica closed");
+ assertTrue(majorityLost.get(_timeout, TimeUnit.SECONDS), "Majority lost is undetected");
- assertEquals("Unexpected facade state",
- ReplicatedEnvironmentFacade.State.RESTARTING,
- master.getFacadeState());
+ assertEquals(ReplicatedEnvironmentFacade.State.RESTARTING, master.getFacadeState(), "Unexpected facade state");
when(masterConfig.getQuorumOverride()).thenReturn(1);
master.reapplyElectableGroupSizeOverride();
- assertTrue(
- "Master did not become available again following the application of the electable group override",
- masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master did not become available again following the application of the electable group override");
}
@Test
@@ -1185,8 +1133,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
ReplicatedEnvironmentConfiguration masterConfig = createReplicatedEnvironmentConfiguration(TEST_NODE_NAME, TEST_NODE_HOST_PORT, false);
ReplicatedEnvironmentFacade master = createReplicatedEnvironmentFacade(TEST_NODE_NAME, masterListener, masterGroupListener, masterConfig);
- assertTrue("Master was not created", masterListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master was not created");
int replicaPort = _portHelper.getNextAvailable();
String replicaNodeHostPort = "localhost:" + replicaPort;
@@ -1197,19 +1145,17 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
new NoopReplicationGroupListener());
replica1.close();
- assertTrue("Node that was master did not become detached after the replica closed",
- masterListener.awaitForStateChange(State.DETACHED, _timeout, TimeUnit.SECONDS));
- assertTrue("Majority lost is undetected", majorityLost.get(_timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.DETACHED, _timeout, TimeUnit.SECONDS),
+ "Node that was master did not become detached after the replica closed");
+ assertTrue(majorityLost.get(_timeout, TimeUnit.SECONDS), "Majority lost is undetected");
- assertEquals("Unexpected facade state",
- ReplicatedEnvironmentFacade.State.RESTARTING,
- master.getFacadeState());
+ assertEquals(ReplicatedEnvironmentFacade.State.RESTARTING, master.getFacadeState(), "Unexpected facade state");
when(masterConfig.isDesignatedPrimary()).thenReturn(true);
master.reapplyDesignatedPrimary();
- assertTrue("Master did not become available again following designated primary",
- masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS));
+ assertTrue(masterListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Master did not become available again following designated primary");
}
@Test
@@ -1305,8 +1251,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
roleListener,
new NoopReplicationGroupListener(),
node1Config);
- assertTrue("Environment was not created",
- roleListener.awaitForStateChange(nodeRole, _timeout, TimeUnit.SECONDS));
+ assertTrue(roleListener.awaitForStateChange(nodeRole, _timeout, TimeUnit.SECONDS),
+ "Environment was not created");
return node;
}
@@ -1400,8 +1346,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
{
TestStateChangeListener stateChangeListener = new TestStateChangeListener();
ReplicatedEnvironmentFacade env = addNode(stateChangeListener, replicationGroupListener);
- assertTrue("Environment was not created", stateChangeListener.awaitForStateChange(State.MASTER,
- _timeout, TimeUnit.SECONDS));
+ assertTrue(stateChangeListener.awaitForStateChange(State.MASTER, _timeout, TimeUnit.SECONDS),
+ "Environment was not created");
return env;
}
@@ -1419,8 +1365,8 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
testStateChangeListener, replicationGroupListener);
boolean awaitForStateChange = testStateChangeListener.awaitForStateChange(State.REPLICA,
_timeout, TimeUnit.SECONDS);
- assertTrue("Replica " + nodeName + " did not go into desired state; current actual state is " + testStateChangeListener.getCurrentActualState(),
- awaitForStateChange);
+ assertTrue(awaitForStateChange, "Replica " + nodeName + " did not go into desired state; current actual state is " +
+ testStateChangeListener.getCurrentActualState());
return replicaEnvironmentFacade;
}
private ReplicatedEnvironmentFacade addNode(String nodeName, String nodeHostPort, boolean designatedPrimary,
@@ -1556,6 +1502,5 @@ public class ReplicatedEnvironmentFacadeTest extends UnitTestBase
public void onException(Exception e)
{
}
-
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/tuple/ConfiguredObjectBindingTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/tuple/ConfiguredObjectBindingTest.java
index 12627b9b21..2eab980c70 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/tuple/ConfiguredObjectBindingTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/tuple/ConfiguredObjectBindingTest.java
@@ -20,15 +20,16 @@
*/
package org.apache.qpid.server.store.berkeleydb.tuple;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.Map;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.UUIDGenerator;
import org.apache.qpid.server.store.ConfiguredObjectRecord;
@@ -41,12 +42,12 @@ public class ConfiguredObjectBindingTest extends UnitTestBase
private ConfiguredObjectRecord _object;
private static final Map<String, Object> DUMMY_ATTRIBUTES_MAP =
- Collections.singletonMap("dummy",(Object) "attributes");
+ Collections.singletonMap("dummy", "attributes");
private static final String DUMMY_TYPE_STRING = "dummyType";
private ConfiguredObjectBinding _configuredObjectBinding;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_configuredObjectBinding = ConfiguredObjectBinding.getInstance();
@@ -65,7 +66,7 @@ public class ConfiguredObjectBindingTest extends UnitTestBase
TupleInput tupleInput = new TupleInput(entryAsBytes);
ConfiguredObjectRecord storedObject = _configuredObjectBinding.entryToObject(tupleInput);
- assertEquals("Unexpected attributes", DUMMY_ATTRIBUTES_MAP, storedObject.getAttributes());
- assertEquals("Unexpected type", DUMMY_TYPE_STRING, storedObject.getType());
+ assertEquals(DUMMY_ATTRIBUTES_MAP, storedObject.getAttributes(), "Unexpected attributes");
+ assertEquals(DUMMY_TYPE_STRING, storedObject.getType(), "Unexpected type");
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/AbstractUpgradeTestCase.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/AbstractUpgradeTestCase.java
index f4efdcd5f1..27a34eaf5a 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/AbstractUpgradeTestCase.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/AbstractUpgradeTestCase.java
@@ -25,24 +25,22 @@ import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPrepare
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.PRIORITY_QUEUE_NAME;
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.QUEUE_NAME;
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.QUEUE_WITH_DLQ_NAME;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.InputStream;
+import java.util.Objects;
import java.util.UUID;
-import com.sleepycat.je.Database;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
-import com.sleepycat.je.Transaction;
-import org.junit.After;
-import org.junit.Before;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.apache.qpid.server.logging.LogSubject;
import org.apache.qpid.server.logging.subjects.TestBlankSubject;
@@ -83,10 +81,11 @@ public abstract class AbstractUpgradeTestCase extends UnitTestBase
private File _storeLocation;
protected Environment _environment;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_storeLocation = copyStore(getStoreDirectoryName());
@@ -108,7 +107,7 @@ public abstract class AbstractUpgradeTestCase extends UnitTestBase
return new Environment(storeLocation, envConfig);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -155,32 +154,24 @@ public abstract class AbstractUpgradeTestCase extends UnitTestBase
{
if (dir.exists())
{
- assertTrue("The provided file " + dir + " is not a directory", dir.isDirectory());
+ assertTrue(dir.isDirectory(), "The provided file " + dir + " is not a directory");
boolean deletedSuccessfully = FileUtils.delete(dir, true);
- assertTrue("Files at '" + dir + "' should have been deleted", deletedSuccessfully);
+ assertTrue(deletedSuccessfully, "Files at '" + dir + "' should have been deleted");
}
}
protected void assertDatabaseRecordCount(String databaseName, final long expectedCountNumber)
{
long count = getDatabaseCount(databaseName);
- assertEquals("Unexpected database '" + databaseName + "' entry number", expectedCountNumber, count);
+ assertEquals(expectedCountNumber, count, "Unexpected database '" + databaseName + "' entry number");
}
protected long getDatabaseCount(String databaseName)
{
- DatabaseCallable<Long> operation = new DatabaseCallable<Long>()
- {
-
- @Override
- public Long call(Database sourceDatabase, Database targetDatabase, Transaction transaction)
- {
- return Long.valueOf(sourceDatabase.count());
-
- }
- };
+ DatabaseCallable<Long> operation =
+ (sourceDatabase, targetDatabase, transaction) -> Long.valueOf(sourceDatabase.count());
Long count = new DatabaseTemplate(_environment, databaseName, null).call(operation);
return count.longValue();
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/DatabaseTemplateTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/DatabaseTemplateTest.java
index 4a0d892a3b..1c3d9dfa21 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/DatabaseTemplateTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/DatabaseTemplateTest.java
@@ -33,8 +33,8 @@ import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -44,7 +44,7 @@ public class DatabaseTemplateTest extends UnitTestBase
private Environment _environment;
private Database _sourceDatabase;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_environment = mock(Environment.class);
@@ -87,5 +87,4 @@ public class DatabaseTemplateTest extends UnitTestBase
verify(databaseOperation).run(eq(_sourceDatabase), isNull(), isNull());
verify(_sourceDatabase).close();
}
-
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/MapJsonSerializerTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/MapJsonSerializerTest.java
index 3ac34b15fa..962e5ba1d9 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/MapJsonSerializerTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/MapJsonSerializerTest.java
@@ -20,13 +20,13 @@
*/
package org.apache.qpid.server.store.berkeleydb.upgrade;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -34,7 +34,7 @@ public class MapJsonSerializerTest extends UnitTestBase
{
private MapJsonSerializer _serializer;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_serializer = new MapJsonSerializer();
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom4to5Test.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom4to5Test.java
index 311cef8b78..558d5e0bf0 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom4to5Test.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom4to5Test.java
@@ -26,9 +26,9 @@ import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPrepare
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.QUEUE_WITH_DLQ_NAME;
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.SELECTOR_TOPIC_NAME;
import static org.apache.qpid.server.store.berkeleydb.BDBStoreUpgradeTestPreparer.TOPIC_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -45,7 +45,8 @@ import com.sleepycat.bind.tuple.LongBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Transaction;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.filter.AMQPFilterTypes;
import org.apache.qpid.server.protocol.v0_8.AMQShortString;
@@ -75,12 +76,12 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
}
@Test
- public void testPerformUpgradeWithHandlerAnsweringYes() throws Exception
+ public void testPerformUpgradeWithHandlerAnsweringYes()
{
UpgradeFrom4To5 upgrade = new UpgradeFrom4To5();
upgrade.performUpgrade(_environment, new StaticAnswerHandler(UpgradeInteractionResponse.YES), getVirtualHost());
- assertQueues(new HashSet<String>(Arrays.asList(QUEUE_NAMES)));
+ assertQueues(new HashSet<>(Arrays.asList(QUEUE_NAMES)));
assertDatabaseRecordCount(DELIVERY_DB_NAME, TOTAL_MESSAGE_NUMBER);
assertDatabaseRecordCount(MESSAGE_META_DATA_DB_NAME, TOTAL_MESSAGE_NUMBER);
@@ -93,7 +94,7 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
final List<BindingRecord> queueBindings = loadBindings();
- assertEquals("Unxpected bindings size", TOTAL_BINDINGS, queueBindings.size());
+ assertEquals(TOTAL_BINDINGS, queueBindings.size(), "Unxpected bindings size");
assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE, "amq.topic", TOPIC_NAME, "");
assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE_WITH_SELECTOR, "amq.topic", SELECTOR_TOPIC_NAME, "testprop='true'");
assertBindingRecord(queueBindings, QUEUE_NAME, "amq.direct", QUEUE_NAME, null);
@@ -106,12 +107,12 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
}
@Test
- public void testPerformUpgradeWithHandlerAnsweringNo() throws Exception
+ public void testPerformUpgradeWithHandlerAnsweringNo()
{
UpgradeFrom4To5 upgrade = new UpgradeFrom4To5();
upgrade.performUpgrade(_environment, new StaticAnswerHandler(UpgradeInteractionResponse.NO), getVirtualHost());
- HashSet<String> queues = new HashSet<String>(Arrays.asList(QUEUE_NAMES));
- assertTrue(NON_DURABLE_QUEUE_NAME + " should be in the list of queues" , queues.remove(NON_DURABLE_QUEUE_NAME));
+ HashSet<String> queues = new HashSet<>(Arrays.asList(QUEUE_NAMES));
+ assertTrue(queues.remove(NON_DURABLE_QUEUE_NAME), NON_DURABLE_QUEUE_NAME + " should be in the list of queues");
assertQueues(queues);
@@ -126,7 +127,7 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
final List<BindingRecord> queueBindings = loadBindings();
- assertEquals("Unxpected list size", TOTAL_BINDINGS - 2, queueBindings.size());
+ assertEquals(TOTAL_BINDINGS - 2, queueBindings.size(), "Unexpected list size");
assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE, "amq.topic", TOPIC_NAME, "");
assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE_WITH_SELECTOR, "amq.topic",
SELECTOR_TOPIC_NAME, "testprop='true'");
@@ -140,7 +141,7 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
private List<BindingRecord> loadBindings()
{
final BindingTuple bindingTuple = new BindingTuple();
- final List<BindingRecord> queueBindings = new ArrayList<BindingRecord>();
+ final List<BindingRecord> queueBindings = new ArrayList<>();
CursorOperation databaseOperation = new CursorOperation()
{
@@ -174,13 +175,13 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
break;
}
}
- assertNotNull("Binding is not found for queue " + queueName + " and exchange " + exchangeName, record);
- assertEquals("Unexpected routing key", routingKey, record.getRoutingKey().toString());
+ assertNotNull(record, "Binding is not found for queue " + queueName + " and exchange " + exchangeName);
+ assertEquals(routingKey, record.getRoutingKey().toString(), "Unexpected routing key");
if (selectorKey != null)
{
- assertEquals("Unexpected selector key for " + queueName, selectorKey,
- record.getArguments().get(AMQPFilterTypes.JMS_SELECTOR.getValue()));
+ assertEquals(selectorKey, record.getArguments().get(AMQPFilterTypes.JMS_SELECTOR.getValue()),
+ "Unexpected selector key for " + queueName);
}
}
@@ -197,7 +198,7 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
{
final QueueEntryKeyBinding queueEntryKeyBinding = new QueueEntryKeyBinding();
final AtomicInteger deliveryCounter = new AtomicInteger();
- final Set<Long> messagesForQueue = new HashSet<Long>();
+ final Set<Long> messagesForQueue = new HashSet<>();
CursorOperation deliveryDatabaseOperation = new CursorOperation()
{
@@ -216,8 +217,8 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
};
new DatabaseTemplate(_environment, DELIVERY_DB_NAME, null).run(deliveryDatabaseOperation);
- assertEquals("Unxpected number of entries in delivery db for queue " + queueName, expectedQueueSize,
- deliveryCounter.get());
+ assertEquals(expectedQueueSize, deliveryCounter.get(),
+ "Unxpected number of entries in delivery db for queue " + queueName);
return messagesForQueue;
}
@@ -244,8 +245,8 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
};
new DatabaseTemplate(_environment, MESSAGE_META_DATA_DB_NAME, null).run(databaseOperation);
- assertEquals("Unxpected number of entries in metadata db for queue " + queueName, expectedQueueSize,
- metadataCounter.get());
+ assertEquals(expectedQueueSize, metadataCounter.get(),
+ "Unxpected number of entries in metadata db for queue " + queueName);
}
private void assertContentForQueue(String queueName, int expectedQueueSize, final Set<Long> messageIdsForQueue)
@@ -273,15 +274,15 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
};
new DatabaseTemplate(_environment, MESSAGE_CONTENT_DB_NAME, null).run(cursorOperation);
- assertEquals("Unxpected number of entries in content db for queue " + queueName, expectedQueueSize,
- contentCounter.get());
+ assertEquals(expectedQueueSize, contentCounter.get(),
+ "Unxpected number of entries in content db for queue " + queueName);
}
private void assertQueues(Set<String> expectedQueueNames)
{
List<AMQShortString> durableSubNames = Collections.emptyList();
final UpgradeFrom4To5.QueueRecordBinding binding = new UpgradeFrom4To5.QueueRecordBinding(durableSubNames);
- final Set<String> actualQueueNames = new HashSet<String>();
+ final Set<String> actualQueueNames = new HashSet<>();
CursorOperation queueNameCollector = new CursorOperation()
{
@@ -297,14 +298,14 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
};
new DatabaseTemplate(_environment, "queueDb_v5", null).run(queueNameCollector);
- assertEquals("Unexpected queue names", expectedQueueNames, actualQueueNames);
+ assertEquals(expectedQueueNames, actualQueueNames, "Unexpected queue names");
}
private void assertQueueHasOwner(String queueName, final String expectedOwner)
{
List<AMQShortString> durableSubNames = Collections.emptyList();
final UpgradeFrom4To5.QueueRecordBinding binding = new UpgradeFrom4To5.QueueRecordBinding(durableSubNames);
- final AtomicReference<String> actualOwner = new AtomicReference<String>();
+ final AtomicReference<String> actualOwner = new AtomicReference<>();
final AtomicBoolean foundQueue = new AtomicBoolean(false);
CursorOperation queueNameCollector = new CursorOperation()
@@ -325,8 +326,8 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
};
new DatabaseTemplate(_environment, "queueDb_v5", null).run(queueNameCollector);
- assertTrue("Could not find queue in database", foundQueue.get());
- assertEquals("Queue has unexpected owner", expectedOwner, actualOwner.get());
+ assertTrue(foundQueue.get(), "Could not find queue in database");
+ assertEquals(expectedOwner, actualOwner.get(), "Queue has unexpected owner");
}
private void assertContent()
@@ -340,9 +341,9 @@ public class UpgradeFrom4to5Test extends AbstractUpgradeTestCase
DatabaseEntry value)
{
long id = LongBinding.entryToLong(key);
- assertTrue("Unexpected id", id > 0);
+ assertTrue(id > 0, "Unexpected id");
ByteBuffer content = contentBinding.entryToObject(value);
- assertNotNull("Unexpected content", content);
+ assertNotNull(content, "Unexpected content");
}
};
new DatabaseTemplate(_environment, MESSAGE_CONTENT_DB_NAME, null).run(contentCursorOperation);
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom5To6Test.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom5To6Test.java
index a5a03b8952..50d4e371f0 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom5To6Test.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom5To6Test.java
@@ -29,9 +29,9 @@ import static org.apache.qpid.server.store.berkeleydb.upgrade.UpgradeFrom5To6.NE
import static org.apache.qpid.server.store.berkeleydb.upgrade.UpgradeFrom5To6.NEW_XID_DB_NAME;
import static org.apache.qpid.server.store.berkeleydb.upgrade.UpgradeFrom5To6.OLD_CONTENT_DB_NAME;
import static org.apache.qpid.server.store.berkeleydb.upgrade.UpgradeFrom5To6.OLD_XID_DB_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.util.ArrayList;
@@ -50,7 +50,9 @@ import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.Transaction;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -134,7 +136,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
}
@Test
- public void testPerformXidUpgrade() throws Exception
+ public void testPerformXidUpgrade()
{
File storeLocation = new File(TMP_FOLDER, getTestName());
storeLocation.mkdirs();
@@ -164,27 +166,21 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
{
final DatabaseEntry value = new DatabaseEntry();
final DatabaseEntry key = getXidKey();
- new DatabaseTemplate(environment, NEW_XID_DB_NAME, null).run(new DatabaseRunnable()
- {
-
- @Override
- public void run(Database xidDatabase, Database nullDatabase, Transaction transaction)
- {
- xidDatabase.get(null, key, value, LockMode.DEFAULT);
- }
- });
+ new DatabaseTemplate(environment, NEW_XID_DB_NAME, null).run((xidDatabase, nullDatabase, transaction) -> xidDatabase.get(null, key, value, LockMode.DEFAULT));
NewPreparedTransactionBinding newBinding = new NewPreparedTransactionBinding();
NewPreparedTransaction newTransaction = newBinding.entryToObject(value);
NewRecordImpl[] newEnqueues = newTransaction.getEnqueues();
NewRecordImpl[] newDequeues = newTransaction.getDequeues();
- assertEquals("Unxpected new enqueus number", 1, newEnqueues.length);
+ assertEquals(1, newEnqueues.length, "Unexpected new enqueues number");
NewRecordImpl enqueue = newEnqueues[0];
- assertEquals("Unxpected queue id", UUIDGenerator.generateQueueUUID("TEST1", getVirtualHost().getName()), enqueue.getId());
- assertEquals("Unxpected message id", 1, enqueue.getMessageNumber());
- assertEquals("Unxpected new dequeues number", 1, newDequeues.length);
+ assertEquals(UUIDGenerator.generateQueueUUID("TEST1", getVirtualHost().getName()), enqueue.getId(),
+ "Unexpected queue id");
+ assertEquals(1, enqueue.getMessageNumber(), "Unexpected message id");
+ assertEquals(1, newDequeues.length, "Unexpected new dequeues number");
NewRecordImpl dequeue = newDequeues[0];
- assertEquals("Unxpected queue id", UUIDGenerator.generateQueueUUID("TEST2", getVirtualHost().getName()), dequeue.getId());
- assertEquals("Unxpected message id", 2, dequeue.getMessageNumber());
+ assertEquals(UUIDGenerator.generateQueueUUID("TEST2", getVirtualHost().getName()), dequeue.getId(),
+ "Unexpected queue id");
+ assertEquals(2, dequeue.getMessageNumber(), "Unexpected message id");
}
private void populateOldXidEntries(Environment environment)
@@ -198,15 +194,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
oldPreparedTransactionBinding.objectToEntry(oldPreparedTransaction, value);
final DatabaseEntry key = getXidKey();
- new DatabaseTemplate(environment, OLD_XID_DB_NAME, null).run(new DatabaseRunnable()
- {
-
- @Override
- public void run(Database xidDatabase, Database nullDatabase, Transaction transaction)
- {
- xidDatabase.put(null, key, value);
- }
- });
+ new DatabaseTemplate(environment, OLD_XID_DB_NAME, null).run((xidDatabase, nullDatabase, transaction) -> xidDatabase.put(null, key, value));
}
protected DatabaseEntry getXidKey()
@@ -232,7 +220,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
DatabaseEntry key, DatabaseEntry value)
{
NewQueueEntryKey newEntryRecord = newBinding.entryToObject(key);
- assertTrue("Unexpected queue id", configuredObjects.containsKey(newEntryRecord.getQueueId()));
+ assertTrue(configuredObjects.containsKey(newEntryRecord.getQueueId()), "Unexpected queue id");
}
};
new DatabaseTemplate(_environment, NEW_DELIVERY_DB_NAME, null).run(cursorOperation);
@@ -286,30 +274,30 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
private void assertConfiguredObjects() throws Exception
{
Map<UUID, UpgradeConfiguredObjectRecord> configuredObjects = loadConfiguredObjects();
- assertEquals("Unexpected number of configured objects", 21, configuredObjects.size());
+ assertEquals(21, configuredObjects.size(), "Unexpected number of configured objects");
- Set<Map<String, Object>> expected = new HashSet<Map<String, Object>>(12);
- List<UUID> expectedBindingIDs = new ArrayList<UUID>();
+ Set<Map<String, Object>> expected = new HashSet<>(12);
+ List<UUID> expectedBindingIDs = new ArrayList<>();
expected.add(createExpectedQueueMap("myUpgradeQueue", Boolean.FALSE, null, null));
expected.add(createExpectedQueueMap("clientid:mySelectorDurSubName", Boolean.TRUE, "clientid", null));
expected.add(createExpectedQueueMap("clientid:myDurSubName", Boolean.TRUE, "clientid", null));
- final Map<String, Object> queueWithOwnerArguments = new HashMap<String, Object>();
+ final Map<String, Object> queueWithOwnerArguments = new HashMap<>();
queueWithOwnerArguments.put(QueueArgumentsConverter.X_QPID_PRIORITIES, 10);
queueWithOwnerArguments.put(QueueArgumentsConverter.X_QPID_DESCRIPTION, "misused-owner-as-description");
expected.add(createExpectedQueueMap("nonexclusive-with-erroneous-owner", Boolean.FALSE, null,queueWithOwnerArguments));
- final Map<String, Object> priorityQueueArguments = new HashMap<String, Object>();
+ final Map<String, Object> priorityQueueArguments = new HashMap<>();
priorityQueueArguments.put(QueueArgumentsConverter.X_QPID_PRIORITIES, 10);
expected.add(createExpectedQueueMap(PRIORITY_QUEUE_NAME, Boolean.FALSE, null, priorityQueueArguments));
- final Map<String, Object> queueWithDLQArguments = new HashMap<String, Object>();
+ final Map<String, Object> queueWithDLQArguments = new HashMap<>();
queueWithDLQArguments.put("x-qpid-dlq-enabled", true);
queueWithDLQArguments.put("x-qpid-maximum-delivery-count", 2);
expected.add(createExpectedQueueMap(QUEUE_WITH_DLQ_NAME, Boolean.FALSE, null, queueWithDLQArguments));
- final Map<String, Object> dlqArguments = new HashMap<String, Object>();
+ final Map<String, Object> dlqArguments = new HashMap<>();
dlqArguments.put("x-qpid-dlq-enabled", false);
dlqArguments.put("x-qpid-maximum-delivery-count", 0);
expected.add(createExpectedQueueMap(QUEUE_WITH_DLQ_NAME + "_DLQ", Boolean.FALSE, null, dlqArguments));
@@ -333,7 +321,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
expected.add(createExpectedQueueBindingMapAndID(QUEUE_WITH_DLQ_NAME, QUEUE_WITH_DLQ_NAME, "amq.direct", null, expectedBindingIDs));
expected.add(createExpectedQueueBindingMapAndID(QUEUE_WITH_DLQ_NAME + "_DLQ", "dlq", QUEUE_WITH_DLQ_NAME + "_DLE", null, expectedBindingIDs));
- Set<String> expectedTypes = new HashSet<String>();
+ Set<String> expectedTypes = new HashSet<>();
expectedTypes.add(Queue.class.getName());
expectedTypes.add(Exchange.class.getName());
expectedTypes.add(Binding.class.getName());
@@ -343,39 +331,41 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
UpgradeConfiguredObjectRecord object = entry.getValue();
Map<String, Object> deserialized = jsonSerializer.deserialize(object.getAttributes());
- assertTrue("Unexpected entry in a store - json [" + object.getAttributes() + "], map [" + deserialized + "]",
- expected.remove(deserialized));
+ assertTrue(expected.remove(deserialized),
+ "Unexpected entry in a store - json [" + object.getAttributes() + "], map [" + deserialized + "]");
String type = object.getType();
- assertTrue("Unexpected type:" + type, expectedTypes.contains(type));
+ assertTrue(expectedTypes.contains(type), "Unexpected type:" + type);
UUID key = entry.getKey();
- assertNotNull("Key cannot be null", key);
+ assertNotNull(key, "Key cannot be null");
if (type.equals(Exchange.class.getName()))
{
String exchangeName = (String) deserialized.get(Exchange.NAME);
assertNotNull(exchangeName);
- assertEquals("Unexpected key", key, UUIDGenerator.generateExchangeUUID(exchangeName, getVirtualHost().getName()));
+ assertEquals(key, UUIDGenerator.generateExchangeUUID(exchangeName, getVirtualHost().getName()),
+ "Unexpected key");
}
else if (type.equals(Queue.class.getName()))
{
String queueName = (String) deserialized.get(Queue.NAME);
assertNotNull(queueName);
- assertEquals("Unexpected key", key, UUIDGenerator.generateQueueUUID(queueName, getVirtualHost().getName()));
+ assertEquals(key, UUIDGenerator.generateQueueUUID(queueName, getVirtualHost().getName()),
+ "Unexpected key");
}
else if (type.equals(Binding.class.getName()))
{
- assertTrue("unexpected binding id", expectedBindingIDs.remove(key));
+ assertTrue(expectedBindingIDs.remove(key), "Unexpected binding id");
}
}
- assertTrue("Not all expected configured objects found:" + expected, expected.isEmpty());
- assertTrue("Not all expected bindings found:" + expectedBindingIDs, expectedBindingIDs.isEmpty());
+ assertTrue(expected.isEmpty(), "Not all expected configured objects found:" + expected);
+ assertTrue(expectedBindingIDs.isEmpty(), "Not all expected bindings found:" + expectedBindingIDs);
}
private Map<String, Object> createExpectedQueueBindingMapAndID(String queue, String bindingName, String exchangeName, Map<String, String> argumentMap, List<UUID> expectedBindingIDs)
{
- Map<String, Object> expectedQueueBinding = new HashMap<String, Object>();
+ final Map<String, Object> expectedQueueBinding = new HashMap<>();
expectedQueueBinding.put("queue", UUIDGenerator.generateQueueUUID(queue, getVirtualHost().getName()).toString());
expectedQueueBinding.put("name", bindingName);
expectedQueueBinding.put("exchange", UUIDGenerator.generateExchangeUUID(exchangeName, getVirtualHost().getName()).toString());
@@ -391,7 +381,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
private Map<String, Object> createExpectedQueueMap(String name, boolean exclusiveFlag, String owner, Map<String, Object> argumentMap)
{
- Map<String, Object> expectedQueueEntry = new HashMap<String, Object>();
+ final Map<String, Object> expectedQueueEntry = new HashMap<>();
expectedQueueEntry.put(Queue.NAME, name);
expectedQueueEntry.put(Queue.EXCLUSIVE, exclusiveFlag);
expectedQueueEntry.put(Queue.OWNER, owner);
@@ -404,7 +394,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
private Map<String, Object> createExpectedExchangeMap(String name, String type)
{
- Map<String, Object> expectedExchnageEntry = new HashMap<String, Object>();
+ final Map<String, Object> expectedExchnageEntry = new HashMap<>();
expectedExchnageEntry.put(Exchange.NAME, name);
expectedExchnageEntry.put(Exchange.TYPE, type);
expectedExchnageEntry.put(Exchange.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name());
@@ -413,7 +403,7 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
private Map<UUID, UpgradeConfiguredObjectRecord> loadConfiguredObjects()
{
- final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<UUID, UpgradeConfiguredObjectRecord>();
+ final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<>();
final ConfiguredObjectBinding binding = new ConfiguredObjectBinding();
final UpgradeUUIDBinding uuidBinding = new UpgradeUUIDBinding();
CursorOperation configuredObjectsCursor = new CursorOperation()
@@ -442,9 +432,9 @@ public class UpgradeFrom5To6Test extends AbstractUpgradeTestCase
DatabaseEntry key, DatabaseEntry value)
{
long id = LongBinding.entryToLong(key);
- assertTrue("Unexpected id", id > 0);
+ assertTrue(id > 0, "Unexpected id");
byte[] content = contentBinding.entryToObject(value);
- assertNotNull("Unexpected content", content);
+ assertNotNull(content, "Unexpected content");
}
};
new DatabaseTemplate(_environment, NEW_CONTENT_DB_NAME, null).run(contentCursorOperation);
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom7To8Test.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom7To8Test.java
index 9b7cd145d8..402c713c2b 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom7To8Test.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom7To8Test.java
@@ -20,8 +20,8 @@
*/
package org.apache.qpid.server.store.berkeleydb.upgrade;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -37,7 +37,8 @@ import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Transaction;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.Exchange;
import org.apache.qpid.server.model.LifetimePolicy;
@@ -83,7 +84,7 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
private void assertConfiguredObjectHierarchy()
{
Map<UpgradeHierarchyKey, UUID> hierarchy = loadConfiguredObjectHierarchy();
- assertEquals("Unexpected number of configured objects", 13, hierarchy.size());
+ assertEquals(13, hierarchy.size(), "Unexpected number of configured objects");
UUID vhUuid = UUIDGenerator.generateVhostUUID(getVirtualHost().getName());
UUID myExchUuid = UUIDGenerator.generateExchangeUUID("myexch", getVirtualHost().getName());
@@ -120,17 +121,17 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
Map<UpgradeHierarchyKey, UUID> hierarchy,
UpgradeHierarchyKey childHierarchyKey, UUID parentUUID)
{
- assertTrue("Expected hierarchy entry does not exist", hierarchy.containsKey(childHierarchyKey));
- assertEquals("Expected hierarchy entry does not exist", parentUUID, hierarchy.get(childHierarchyKey));
+ assertTrue(hierarchy.containsKey(childHierarchyKey), "Expected hierarchy entry does not exist");
+ assertEquals(parentUUID, hierarchy.get(childHierarchyKey), "Expected hierarchy entry does not exist");
}
private void assertConfiguredObjects() throws Exception
{
Map<UUID, UpgradeConfiguredObjectRecord> configuredObjects = loadConfiguredObjects();
- assertEquals("Unexpected number of configured objects", 11, configuredObjects.size());
+ assertEquals(11, configuredObjects.size(), "Unexpected number of configured objects");
- Map<UUID, Map<String, Object>> expected = new HashMap<UUID, Map<String, Object>>();
+ Map<UUID, Map<String, Object>> expected = new HashMap<>();
String configVersion = "0.3";
expected.putAll(createExpectedVirtualHost(configVersion));
@@ -159,28 +160,30 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
String actualJson = object.getAttributes();
Map<String, Object> actualDeserializedAttributes = jsonSerializer.deserialize(actualJson);
- assertTrue("Entry UUID " + actualKey + " of type " + actualType + " is unexpected", expected.containsKey(actualKey));
+ assertTrue(expected.containsKey(actualKey), "Entry UUID " + actualKey + " of type " + actualType +
+ " is unexpected");
Map<String, Object> expectedDeserializedAttributes = expected.get(actualKey);
- assertEquals("Entry UUID " + actualKey + " of type " + actualType + " has uenxpected deserialised value, json was: " + actualJson,
- expectedDeserializedAttributes, actualDeserializedAttributes);
+ assertEquals(expectedDeserializedAttributes, actualDeserializedAttributes,
+ "Entry UUID " + actualKey + " of type " + actualType +
+ " has unexpected deserialised value, json was: " + actualJson);
}
}
private Map<UUID, Map<String, Object>> createExpectedVirtualHost(String modelVersion)
{
- Map<String, Object> expectedVirtualHostEntry = new HashMap<String, Object>();
+ final Map<String, Object> expectedVirtualHostEntry = new HashMap<>();
expectedVirtualHostEntry.put("modelVersion", modelVersion);
expectedVirtualHostEntry.put(VirtualHost.NAME, getVirtualHost().getName());
- UUID expectedUUID = UUIDGenerator.generateVhostUUID(getVirtualHost().getName());
+ final UUID expectedUUID = UUIDGenerator.generateVhostUUID(getVirtualHost().getName());
return Collections.singletonMap(expectedUUID, expectedVirtualHostEntry);
}
private Map<UUID, Map<String, Object>> createExpectedQueue(String queueName, boolean exclusiveFlag, String owner, Map<String, Object> argumentMap)
{
- Map<String, Object> expectedQueueEntry = new HashMap<String, Object>();
+ final Map<String, Object> expectedQueueEntry = new HashMap<>();
expectedQueueEntry.put(Queue.NAME, queueName);
expectedQueueEntry.put(Queue.EXCLUSIVE, exclusiveFlag);
expectedQueueEntry.put(Queue.OWNER, owner);
@@ -190,33 +193,33 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
{
expectedQueueEntry.put(ARGUMENTS, argumentMap);
}
- UUID expectedUUID = UUIDGenerator.generateQueueUUID(queueName, getVirtualHost().getName());
+ final UUID expectedUUID = UUIDGenerator.generateQueueUUID(queueName, getVirtualHost().getName());
return Collections.singletonMap(expectedUUID, expectedQueueEntry);
}
private Map<UUID, Map<String, Object>> createExpectedExchangeMap(String exchangeName, String type)
{
- Map<String, Object> expectedExchangeMap = new HashMap<String, Object>();
+ final Map<String, Object> expectedExchangeMap = new HashMap<>();
expectedExchangeMap.put(Exchange.NAME, exchangeName);
expectedExchangeMap.put(Exchange.TYPE, type);
expectedExchangeMap.put(Exchange.LIFETIME_POLICY, LifetimePolicy.PERMANENT.name());
- UUID expectedUUID = UUIDGenerator.generateExchangeUUID(exchangeName, getVirtualHost().getName());
+ final UUID expectedUUID = UUIDGenerator.generateExchangeUUID(exchangeName, getVirtualHost().getName());
return Collections.singletonMap(expectedUUID, expectedExchangeMap);
}
private Map<UUID, Map<String, Object>> createExpectedBindingMap(String queueName, String bindingName, String exchangeName, Map<String, String> argumentMap)
{
- Map<String, Object> expectedBinding = new HashMap<String, Object>();
+ final Map<String, Object> expectedBinding = new HashMap<>();
expectedBinding.put("name", bindingName);
expectedBinding.put("arguments", argumentMap == null ? Collections.emptyMap() : argumentMap);
- UUID expectedUUID = UUIDGenerator.generateBindingUUID(exchangeName, queueName, bindingName, getVirtualHost().getName());
+ final UUID expectedUUID = UUIDGenerator.generateBindingUUID(exchangeName, queueName, bindingName, getVirtualHost().getName());
return Collections.singletonMap(expectedUUID, expectedBinding);
}
private Map<UUID, UpgradeConfiguredObjectRecord> loadConfiguredObjects()
{
- final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<UUID, UpgradeConfiguredObjectRecord>();
+ final Map<UUID, UpgradeConfiguredObjectRecord> configuredObjectsRecords = new HashMap<>();
final UpgradeConfiguredObjectBinding binding = new UpgradeConfiguredObjectBinding();
final UpgradeUUIDBinding uuidBinding = new UpgradeUUIDBinding();
CursorOperation configuredObjectsCursor = new CursorOperation()
@@ -237,7 +240,7 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
private Map<UpgradeHierarchyKey, UUID> loadConfiguredObjectHierarchy()
{
- final Map<UpgradeHierarchyKey, UUID> hierarchyRecords = new HashMap<UpgradeHierarchyKey, UUID>();
+ final Map<UpgradeHierarchyKey, UUID> hierarchyRecords = new HashMap<>();
final UpgradeHierarchyKeyBinding hierarchyKeyBinding = new UpgradeHierarchyKeyBinding();
final UpgradeUUIDBinding uuidParentBinding = new UpgradeUUIDBinding();
CursorOperation hierarchyCursor = new CursorOperation()
@@ -262,8 +265,7 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
{
String type = tupleInput.readString();
String json = tupleInput.readString();
- UpgradeConfiguredObjectRecord configuredObject = new UpgradeConfiguredObjectRecord(type, json);
- return configuredObject;
+ return new UpgradeConfiguredObjectRecord(type, json);
}
@Override
@@ -359,12 +361,7 @@ public class UpgradeFrom7To8Test extends AbstractUpgradeTestCase
{
return false;
}
- if (!_parentType.equals(that._parentType))
- {
- return false;
- }
-
- return true;
+ return _parentType.equals(that._parentType);
}
@Override
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom8To9Test.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom8To9Test.java
index b64623fe44..6701d5a1b2 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom8To9Test.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgradeFrom8To9Test.java
@@ -21,8 +21,7 @@
package org.apache.qpid.server.store.berkeleydb.upgrade;
-
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
@@ -31,7 +30,8 @@ import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Transaction;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
public class UpgradeFrom8To9Test extends AbstractUpgradeTestCase
{
@@ -45,7 +45,7 @@ public class UpgradeFrom8To9Test extends AbstractUpgradeTestCase
}
@Test
- public void testPerformUpgrade() throws Exception
+ public void testPerformUpgrade()
{
UpgradeFrom8To9 upgrade = new UpgradeFrom8To9();
upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost());
@@ -54,8 +54,8 @@ public class UpgradeFrom8To9Test extends AbstractUpgradeTestCase
assertDatabaseRecordCount(PREFERENCES_VERSION_DB_NAME, 1);
List<String> versions = loadVersions();
- assertEquals("Unexpected number of versions loaded", 1, versions.size());
- assertEquals("Unexpected version", "6.1", versions.get(0));
+ assertEquals(1, versions.size(), "Unexpected number of versions loaded");
+ assertEquals("6.1", versions.get(0), "Unexpected version");
}
private List<String> loadVersions()
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderFailOnNewerVersionTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderFailOnNewerVersionTest.java
index 745f100786..157ced9d7e 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderFailOnNewerVersionTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderFailOnNewerVersionTest.java
@@ -20,8 +20,8 @@
*/
package org.apache.qpid.server.store.berkeleydb.upgrade;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.je.Cursor;
@@ -29,8 +29,9 @@ import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.OperationStatus;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.store.berkeleydb.BDBConfigurationStore;
import org.apache.qpid.server.util.ServerScopedRuntimeException;
@@ -45,7 +46,7 @@ public class UpgraderFailOnNewerVersionTest extends AbstractUpgradeTestCase
return "bdbstore-v999";
}
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
super.setUp();
@@ -76,9 +77,9 @@ public class UpgraderFailOnNewerVersionTest extends AbstractUpgradeTestCase
}
@Test
- public void testUpgrade() throws Exception
+ public void testUpgrade()
{
- assertEquals("Unexpected store version", 999, getStoreVersion());
+ assertEquals(999, getStoreVersion(), "Unexpected store version");
try
{
_upgrader.upgradeIfNecessary();
@@ -86,8 +87,8 @@ public class UpgraderFailOnNewerVersionTest extends AbstractUpgradeTestCase
}
catch(ServerScopedRuntimeException ex)
{
- assertEquals("Incorrect exception thrown", "Database version 999 is higher than the most recent known version: "
- + BDBConfigurationStore.VERSION, ex.getMessage());
+ assertEquals("Database version 999 is higher than the most recent known version: " +
+ BDBConfigurationStore.VERSION, ex.getMessage(), "Incorrect exception thrown");
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderTest.java
index 09c65165e9..d8f9547767 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/upgrade/UpgraderTest.java
@@ -20,9 +20,9 @@
*/
package org.apache.qpid.server.store.berkeleydb.upgrade;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.util.ArrayList;
@@ -37,8 +37,9 @@ import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
import org.apache.qpid.server.store.berkeleydb.BDBConfigurationStore;
@@ -54,7 +55,7 @@ public class UpgraderTest extends AbstractUpgradeTestCase
return "bdbstore-v4";
}
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
super.setUp();
@@ -85,16 +86,16 @@ public class UpgraderTest extends AbstractUpgradeTestCase
}
@Test
- public void testUpgrade() throws Exception
+ public void testUpgrade()
{
- assertEquals("Unexpected store version", -1, getStoreVersion(_environment));
+ assertEquals(-1, getStoreVersion(_environment), "Unexpected store version");
_upgrader.upgradeIfNecessary();
- assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(_environment));
+ assertEquals(BDBConfigurationStore.VERSION, getStoreVersion(_environment), "Unexpected store version");
assertContent();
}
@Test
- public void testEmptyDatabaseUpgradeDoesNothing() throws Exception
+ public void testEmptyDatabaseUpgradeDoesNothing()
{
File nonExistentStoreLocation = new File(TMP_FOLDER, getTestName());
deleteDirectoryIfExists(nonExistentStoreLocation);
@@ -109,8 +110,9 @@ public class UpgraderTest extends AbstractUpgradeTestCase
List<String> databaseNames = emptyEnvironment.getDatabaseNames();
List<String> expectedDatabases = new ArrayList<String>();
expectedDatabases.add(Upgrader.VERSION_DB_NAME);
- assertEquals("Expectedonly VERSION table in initially empty store after upgrade: ", expectedDatabases, databaseNames);
- assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(emptyEnvironment));
+ assertEquals(expectedDatabases, databaseNames,
+ "Expectedonly VERSION table in initially empty store after upgrade: ");
+ assertEquals(BDBConfigurationStore.VERSION, getStoreVersion(emptyEnvironment), "Unexpected store version");
}
finally
@@ -131,10 +133,10 @@ public class UpgraderTest extends AbstractUpgradeTestCase
DatabaseEntry value)
{
long id = LongBinding.entryToLong(key);
- assertTrue("Unexpected id", id > 0);
+ assertTrue(id > 0, "Unexpected id");
QpidByteBuffer content = contentBinding.entryToObject(value);
- assertNotNull("Unexpected content", content);
- assertTrue("Expected content", content.hasRemaining());
+ assertNotNull(content, "Unexpected content");
+ assertTrue(content.hasRemaining(), "Expected content");
}
};
new DatabaseTemplate(_environment, "MESSAGE_CONTENT", null).run(contentCursorOperation);
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/virtualhost/berkeleydb/BDBVirtualHostImplTest.java b/bdbstore/src/test/java/org/apache/qpid/server/virtualhost/berkeleydb/BDBVirtualHostImplTest.java
index de5f99ad25..72407ebafa 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/virtualhost/berkeleydb/BDBVirtualHostImplTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/virtualhost/berkeleydb/BDBVirtualHostImplTest.java
@@ -20,20 +20,19 @@
*/
package org.apache.qpid.server.virtualhost.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.UUID;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.model.BrokerTestHelper;
@@ -48,10 +47,11 @@ public class BDBVirtualHostImplTest extends UnitTestBase
private File _storePath;
private VirtualHostNode<?> _node;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_storePath = TestFileUtils.createTestDirectory();
@@ -61,7 +61,7 @@ public class BDBVirtualHostImplTest extends UnitTestBase
BrokerTestHelper.createBrokerMock());
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
if (_storePath != null)
@@ -75,7 +75,7 @@ public class BDBVirtualHostImplTest extends UnitTestBase
{
String hostName = getTestName();
File file = new File(_storePath + File.separator + hostName);
- assertTrue("Empty file is not created", file.createNewFile());
+ assertTrue(file.createNewFile(), "Empty file is not created");
Map<String, Object> attributes = new HashMap<>();
attributes.put(BDBVirtualHost.ID, UUID.randomUUID());
attributes.put(BDBVirtualHost.TYPE, BDBVirtualHostImpl.VIRTUAL_HOST_TYPE);
@@ -90,8 +90,8 @@ public class BDBVirtualHostImplTest extends UnitTestBase
}
catch (IllegalConfigurationException e)
{
- assertTrue("Unexpected exception " + e.getMessage(),
- e.getMessage().startsWith("Cannot open virtual host message store"));
+ assertTrue(e.getMessage().startsWith("Cannot open virtual host message store"),
+ "Unexpected exception " + e.getMessage());
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHARemoteReplicationNodeTest.java b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHARemoteReplicationNodeTest.java
index 0b62e3d61b..1fdc958495 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHARemoteReplicationNodeTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHARemoteReplicationNodeTest.java
@@ -19,11 +19,9 @@
package org.apache.qpid.server.virtualhostnode.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyMap;
@@ -40,12 +38,13 @@ import java.security.Principal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
import org.apache.qpid.server.configuration.updater.TaskExecutor;
@@ -69,41 +68,38 @@ public class BDBHARemoteReplicationNodeTest extends UnitTestBase
{
private final AccessControl _mockAccessControl = mock(AccessControl.class);
- private Broker _broker;
- private TaskExecutor _taskExecutor;
private BDBHAVirtualHostNode<?> _virtualHostNode;
- private DurableConfigurationStore _configStore;
private ReplicatedEnvironmentFacade _facade;
-
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_facade = mock(ReplicatedEnvironmentFacade.class);
- _broker = BrokerTestHelper.createBrokerMock();
+ Broker broker = BrokerTestHelper.createBrokerMock();
- _taskExecutor = new CurrentThreadTaskExecutor();
- _taskExecutor.start();
- when(_broker.getTaskExecutor()).thenReturn(_taskExecutor);
- when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
+ TaskExecutor taskExecutor = new CurrentThreadTaskExecutor();
+ taskExecutor.start();
+ when(broker.getTaskExecutor()).thenReturn(taskExecutor);
+ when(broker.getChildExecutor()).thenReturn(taskExecutor);
_virtualHostNode = BrokerTestHelper.mockWithSystemPrincipalAndAccessControl(BDBHAVirtualHostNode.class,
mock(Principal.class),
_mockAccessControl);
- _configStore = mock(DurableConfigurationStore.class);
- when(_virtualHostNode.getConfigurationStore()).thenReturn(_configStore);
+ DurableConfigurationStore configStore = mock(DurableConfigurationStore.class);
+ when(_virtualHostNode.getConfigurationStore()).thenReturn(configStore);
// Virtualhost needs the EventLogger from the SystemContext.
- when(_virtualHostNode.getParent()).thenReturn(_broker);
+ when(_virtualHostNode.getParent()).thenReturn(broker);
doReturn(VirtualHostNode.class).when(_virtualHostNode).getCategoryClass();
- ConfiguredObjectFactory objectFactory = _broker.getObjectFactory();
+ ConfiguredObjectFactory objectFactory = broker.getObjectFactory();
when(_virtualHostNode.getModel()).thenReturn(objectFactory.getModel());
- when(_virtualHostNode.getTaskExecutor()).thenReturn(_taskExecutor);
- when(_virtualHostNode.getChildExecutor()).thenReturn(_taskExecutor);
+ when(_virtualHostNode.getTaskExecutor()).thenReturn(taskExecutor);
+ when(_virtualHostNode.getChildExecutor()).thenReturn(taskExecutor);
}
@@ -229,6 +225,4 @@ public class BDBHARemoteReplicationNodeTest extends UnitTestBase
node.create();
return node;
}
-
-
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java
index 8cba10bc6b..386a288b84 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java
@@ -20,11 +20,9 @@
*/
package org.apache.qpid.server.virtualhostnode.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@@ -34,14 +32,14 @@ import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-import org.hamcrest.Description;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.mockito.ArgumentMatcher;
import org.apache.qpid.server.logging.EventLogger;
@@ -61,14 +59,15 @@ import org.apache.qpid.test.utils.VirtualHostNodeStoreType;
*/
public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
{
- private final PortHelper _portHelper = new PortHelper();
private BDBHAVirtualHostNodeTestHelper _helper;
private EventLogger _eventLogger;
+ private final PortHelper _portHelper = new PortHelper();
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_helper = new BDBHAVirtualHostNodeTestHelper(getTestName());
_eventLogger = mock(EventLogger.class);
@@ -76,7 +75,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
when(context.getEventLogger()).thenReturn(_eventLogger);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
try
@@ -111,11 +110,11 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
// stop node to avoid running into race when role change is reported after we performed the check
node1.stop();
- assertEquals("Unexpected VHN log subject",
- "[grp(/group)/vhn(/node1)] ",
- node1.getVirtualHostNodeLogSubject().getLogString());
+ assertEquals("[grp(/group)/vhn(/node1)] ", node1.getVirtualHostNodeLogSubject().getLogString(),
+ "Unexpected VHN log subject");
- assertEquals("Unexpected group log subject", "[grp(/group)] ", node1.getGroupLogSubject().getLogString());
+ assertEquals("[grp(/group)] ", node1.getGroupLogSubject().getLogString(),
+ "Unexpected group log subject");
String attributes = String.format(
"{address=%s,context={je.rep.insufficientReplicasTimeout=2 s, je.rep.replicaAckTimeout=2 s},createdTime=%s,groupName=%s,helperAddress=%s,id=%s,lastUpdatedTime=%s,name=%s,permittedNodes=[%s],storePath=%s,type=%s,virtualHostInitialConfiguration={\n \"type\" : \"BDB_HA\"\n}}",
@@ -178,7 +177,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
reset(_eventLogger);
- node1.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.PRIORITY, 10));
+ node1.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.PRIORITY, 10));
// make sure that task executor thread finishes all scheduled tasks
node1.stop();
@@ -203,7 +202,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
reset(_eventLogger);
- node1.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1));
+ node1.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1));
// make sure that task executor thread finishes all scheduled tasks
node1.stop();
@@ -228,7 +227,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
reset(_eventLogger);
- node1.setAttributes(Collections.<String, Object>singletonMap(BDBHAVirtualHostNode.DESIGNATED_PRIMARY, true));
+ node1.setAttributes(Collections.singletonMap(BDBHAVirtualHostNode.DESIGNATED_PRIMARY, true));
// make sure that task executor thread finishes all scheduled tasks
node1.stop();
@@ -254,7 +253,6 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
reset(_eventLogger);
-
Map<String, Object> node2Attributes = _helper.createNodeAttributes("node2", groupName, "localhost:" + node2PortNumber, helperAddress, nodeName);
BDBHAVirtualHostNodeImpl node2 = (BDBHAVirtualHostNodeImpl)_helper.createHaVHN(node2Attributes);
_helper.awaitRemoteNodes(node1, 1);
@@ -329,19 +327,17 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
Map<String, Object> node2Attributes = _helper.createNodeAttributes("node2", groupName, "localhost:" + node2PortNumber, helperAddress, nodeName);
BDBHAVirtualHostNodeImpl node2 = (BDBHAVirtualHostNodeImpl)_helper.createHaVHN(node2Attributes);
- assertTrue("Remote node was not added during expected period of time",
- remoteNodeAdded.await(10, TimeUnit.SECONDS));
+ assertTrue(remoteNodeAdded.await(10, TimeUnit.SECONDS),
+ "Remote node was not added during expected period of time");
BDBHARemoteReplicationNodeImpl remoteNode = (BDBHARemoteReplicationNodeImpl)node1.getRemoteReplicationNodes().iterator().next();
waitForRemoteNodeToAttainRole(remoteNode, EnumSet.of(NodeRole.REPLICA));
-
reset(_eventLogger);
// close remote node
node2.close();
-
waitForRemoteNodeToAttainRole(remoteNode, EnumSet.of(NodeRole.UNREACHABLE));
// make sure that task executor thread finishes all scheduled tasks
@@ -418,9 +414,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
static class LogMessageMatcher implements ArgumentMatcher<LogMessage>
{
private final String _expectedMessage;
- private String _expectedMessageFailureDescription = null;
private final String _expectedHierarchy;
- private String _expectedHierarchyFailureDescription = null;
public LogMessageMatcher(String expectedMessage, String expectedHierarchy)
{
@@ -431,25 +425,14 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
@Override
public boolean matches(LogMessage logMessage)
{
- boolean expectedMessageMatches = _expectedMessage.equals(logMessage.toString());
- if (!expectedMessageMatches)
- {
- _expectedMessageFailureDescription = "Expected message does not match. Expected: " + _expectedMessage + ", actual: " + logMessage.toString();
- }
- boolean expectedHierarchyMatches = _expectedHierarchy.equals(logMessage.getLogHierarchy());
- if (!expectedHierarchyMatches)
- {
- _expectedHierarchyFailureDescription = "Expected hierarchy does not match. Expected: " + _expectedHierarchy + ", actual: " + logMessage.getLogHierarchy();
- }
-
- return expectedMessageMatches && expectedHierarchyMatches;
+ return _expectedMessage.equals(logMessage.toString()) &&
+ _expectedHierarchy.equals(logMessage.getLogHierarchy());
}
}
static class LogSubjectMatcher implements ArgumentMatcher<LogSubject>
{
private final LogSubject _logSubject;
- private String _failureDescription = null;
public LogSubjectMatcher(LogSubject logSubject)
{
@@ -459,12 +442,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends UnitTestBase
@Override
public boolean matches(LogSubject logSubject)
{
- final boolean foundAMatch = _logSubject.toLogString().equals(logSubject.toLogString());
- if (!foundAMatch)
- {
- _failureDescription = "LogSubject does not match. Expected: " + _logSubject.toLogString() + ", actual : " + logSubject.toLogString();
- }
- return foundAMatch;
+ return _logSubject.toLogString().equals(logSubject.toLogString());
}
}
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java
index 90047a95fb..8b4f7e25d3 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java
@@ -20,9 +20,9 @@
*/
package org.apache.qpid.server.virtualhostnode.berkeleydb;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.when;
import java.io.File;
@@ -69,7 +69,6 @@ public class BDBHAVirtualHostNodeTestHelper
{
private static final Logger LOGGER = LoggerFactory.getLogger(BDBHAVirtualHostNodeTestHelper.class);
- private final String _testName;
private final Broker<?> _broker;
private final File _bdbStorePath;
private final TaskExecutor _taskExecutor;
@@ -79,9 +78,8 @@ public class BDBHAVirtualHostNodeTestHelper
private final int _sleepInterval;
private final int _waitForVirtualhostInterval;
- public BDBHAVirtualHostNodeTestHelper(String testName) throws Exception
+ public BDBHAVirtualHostNodeTestHelper(String testName)
{
- _testName = testName;
_broker = BrokerTestHelper.createBrokerMock();
_taskExecutor = new TaskExecutorImpl();
@@ -90,7 +88,7 @@ public class BDBHAVirtualHostNodeTestHelper
when(_broker.getChildExecutor()).thenReturn(_taskExecutor);
when(_broker.getContextValue(Long.class, BDBVirtualHost.QPID_BROKER_BDB_TOTAL_CACHE_SIZE)).thenReturn(BDBVirtualHost.BDB_MIN_CACHE_SIZE);
- _bdbStorePath = new File(UnitTestBase.TMP_FOLDER, _testName + "." + System.currentTimeMillis());
+ _bdbStorePath = new File(UnitTestBase.TMP_FOLDER, testName + "." + System.currentTimeMillis());
_bdbStorePath.deleteOnExit();
_numberOfSleeps = Integer.getInteger("BDBHAVirtualHostNodeTestHelper.numberOfSleepsOnChangeWaiting", 50);
_sleepInterval = Integer.getInteger("BDBHAVirtualHostNodeTestHelper.sleepIntervalOnChangeWaiting", 100);
@@ -152,7 +150,7 @@ public class BDBHAVirtualHostNodeTestHelper
int counter = 0;
@SuppressWarnings("rawtypes")
- Collection<? extends RemoteReplicationNode> remoteNodes = null;
+ Collection<? extends RemoteReplicationNode> remoteNodes;
do
{
remoteNodes = node.getRemoteReplicationNodes();
@@ -164,7 +162,7 @@ public class BDBHAVirtualHostNodeTestHelper
}
// TODO: 30 seconds is quite a lot to wait, we need to reduce this limit
while(remoteNodes.size() != expectedNodeNumber && counter<100);
- assertEquals("Unexpected node number", expectedNodeNumber, node.getRemoteReplicationNodes().size());
+ assertEquals(expectedNodeNumber, node.getRemoteReplicationNodes().size(), "Unexpected node number");
}
public void awaitForAttributeChange(ConfiguredObject<?> object, String name, Object expectedValue) throws InterruptedException
@@ -175,7 +173,7 @@ public class BDBHAVirtualHostNodeTestHelper
Thread.sleep(100);
awaitCounter++;
}
- assertEquals("Unexpected attribute " + name + " on " + object, expectedValue, object.getAttribute(name) );
+ assertEquals(expectedValue, object.getAttribute(name), "Unexpected attribute " + name + " on " + object);
}
public BDBHAVirtualHostNode<?> awaitAndFindNodeInRole(NodeRole desiredRole) throws InterruptedException
@@ -253,8 +251,8 @@ public class BDBHAVirtualHostNodeTestHelper
iterationCounter++;
}
while(!inRole && iterationCounter < _numberOfSleeps);
- assertTrue("Node " + node.getName() + " did not transit into role " + Arrays.toString(roleName)
- + " Node role is " + node.getRole(), inRole);
+ assertTrue(inRole, "Node " + node.getName() + " did not transit into role " + Arrays.toString(roleName) +
+ " Node role is " + node.getRole());
}
public BDBHAVirtualHostNode<?> createAndStartHaVHN(Map<String, Object> attributes) throws InterruptedException
@@ -267,7 +265,7 @@ public class BDBHAVirtualHostNodeTestHelper
{
node.start();
assertNodeRole(node, NodeRole.MASTER, NodeRole.REPLICA);
- assertEquals("Unexpected node state", State.ACTIVE, node.getState());
+ assertEquals(State.ACTIVE, node.getState(), "Unexpected node state");
return node;
}
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeTest.java b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeTest.java
index 0c77bac627..8211fad98a 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeTest.java
@@ -20,21 +20,20 @@
*/
package org.apache.qpid.server.virtualhostnode.berkeleydb;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.when;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.UUID;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
@@ -51,10 +50,11 @@ public class BDBVirtualHostNodeTest extends UnitTestBase
private Broker<?> _broker;
private File _storePath;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- assumeThat(getVirtualHostNodeStoreType(), is(equalTo(VirtualHostNodeStoreType.BDB)));
+ assumeTrue(Objects.equals(getVirtualHostNodeStoreType(), VirtualHostNodeStoreType.BDB),
+ "VirtualHostNodeStoreType should be BDB");
_broker = BrokerTestHelper.createBrokerMock();
TaskExecutor taskExecutor = CurrentThreadTaskExecutor.newStartedInstance();
@@ -64,7 +64,7 @@ public class BDBVirtualHostNodeTest extends UnitTestBase
_storePath = TestFileUtils.createTestDirectory();
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
if (_storePath != null)
@@ -78,7 +78,7 @@ public class BDBVirtualHostNodeTest extends UnitTestBase
{
String nodeName = getTestName();
File file = new File(_storePath + File.separator + nodeName);
- assertTrue("Empty file is not created", file.createNewFile());
+ assertTrue(file.createNewFile(), "Empty file is not created");
Map<String, Object> attributes = new HashMap<>();
attributes.put(BDBVirtualHostNode.ID, UUID.randomUUID());
attributes.put(BDBVirtualHostNode.TYPE, BDBVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE);
@@ -93,8 +93,8 @@ public class BDBVirtualHostNodeTest extends UnitTestBase
}
catch (IllegalConfigurationException e)
{
- assertTrue("Unexpected exception " + e.getMessage(),
- e.getMessage().startsWith("Cannot open node configuration store"));
+ assertTrue(e.getMessage().startsWith("Cannot open node configuration store"),
+ "Unexpected exception " + e.getMessage());
}
}
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
index da00491bd7..4cd7b76356 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBAMQP10V0UpgradeTest.java
@@ -20,12 +20,7 @@
package org.apache.qpid.server.store.berkeleydb;
import static org.apache.qpid.systests.JmsTestBase.DEFAULT_BROKER_CONFIG;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.security.MessageDigest;
@@ -36,8 +31,9 @@ import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import com.google.common.base.Objects;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.util.StringUtil;
@@ -61,11 +57,12 @@ public class BDBAMQP10V0UpgradeTest extends UpgradeTestBase
{
private static final long EXPECTED_MESSAGE_LENGTH = 256 * 1024;
- @BeforeClass
+ @BeforeAll
public static void verifyClient()
{
- assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
- assumeThat(getProtocol(), is(equalTo(Protocol.AMQP_1_0)));
+ assumeTrue("BDB".equals(System.getProperty("virtualhostnode.type", "BDB")),
+ "System property 'virtualhostnode.type' should be 'BDB'");
+ assumeTrue(Objects.equal(getProtocol(), Protocol.AMQP_1_0), "AMQP protocol should be 1.0");
}
@Test
@@ -80,7 +77,7 @@ public class BDBAMQP10V0UpgradeTest extends UpgradeTestBase
MessageConsumer consumer = session.createConsumer(queue);
Message message = consumer.receive(getReceiveTimeout());
- assertThat("Recovered message not received", message, is(instanceOf(BytesMessage.class)));
+ assumeTrue(message instanceof BytesMessage,"Recovered message not received");
BytesMessage bytesMessage = ((BytesMessage) message);
long length = bytesMessage.getBodyLength();
@@ -88,11 +85,11 @@ public class BDBAMQP10V0UpgradeTest extends UpgradeTestBase
byte[] content = new byte[(int) length];
bytesMessage.readBytes(content);
- assertThat("Unexpected content length", length, is(equalTo(EXPECTED_MESSAGE_LENGTH)));
- assertThat("Message should carry expectedShaHash property", expectedContentHash, is(notNullValue()));
+ assumeTrue(Objects.equal(EXPECTED_MESSAGE_LENGTH, length), "Unexpected content length");
+ assumeTrue(expectedContentHash != null, "Message should carry expectedShaHash property");
String contentHash = computeContentHash(content);
- assertThat("Unexpected content hash", expectedContentHash, is(equalTo(contentHash)));
+ assumeTrue(Objects.equal(expectedContentHash, contentHash), "Unexpected content hash");
session.commit();
}
finally
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
index d93ec50efa..724c37834f 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBUpgradeTest.java
@@ -23,15 +23,13 @@ package org.apache.qpid.server.store.berkeleydb;
import static org.apache.qpid.systests.JmsTestBase.DEFAULT_BROKER_CONFIG;
import static org.apache.qpid.systests.Utils.INDEX;
import static org.apache.qpid.systests.Utils.sendMessages;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.Collection;
import java.util.Collections;
@@ -52,8 +50,9 @@ import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import com.google.common.base.Objects;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.AlternateBinding;
import org.apache.qpid.server.model.Exchange;
@@ -84,11 +83,12 @@ public class BDBUpgradeTest extends UpgradeTestBase
private static final String PRIORITY_QUEUE_NAME = "myPriorityQueue";
private static final String QUEUE_WITH_DLQ_NAME = "myQueueWithDLQ";
- @BeforeClass
+ @BeforeAll
public static void verifyClient()
{
- assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
- assumeThat(getProtocol(), is(not(equalTo(Protocol.AMQP_1_0))));
+ assumeTrue("BDB".equals(System.getProperty("virtualhostnode.type", "BDB")),
+ "System property 'virtualhostnode.type' should be 'BDB'");
+ assumeTrue(Objects.equal(getProtocol(), Protocol.AMQP_1_0), "AMQP protocol should be 1.0");
}
/**
@@ -125,14 +125,14 @@ public class BDBUpgradeTest extends UpgradeTestBase
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, SELECTOR_SUB_NAME, "testprop='true'", false);
Message migrated = subscriber.receive(getReceiveTimeout());
- assertThat("Failed to receive migrated message", migrated, is(notNullValue()));
+ assertNotNull(migrated, "Failed to receive migrated message");
Message received = subscriber.receive(getReceiveTimeout());
session.commit();
- assertThat("Failed to receive published message", received, is(notNullValue()));
- assertThat("Message is not Text message", received, is(instanceOf(TextMessage.class)));
- assertThat("Unexpected text", ((TextMessage) received).getText(), is(equalTo("B")));
- assertThat("Unexpected index", received.getIntProperty("ID"), is(equalTo(index)));
+ assertNotNull(received, "Failed to receive published message");
+ assertTrue(received instanceof TextMessage, "Message is not Text message");
+ assertEquals("B", ((TextMessage) received).getText(), "Unexpected text");
+ assertEquals(received.getIntProperty("ID"), index, "Unexpected index");
session.close();
}
@@ -174,21 +174,21 @@ public class BDBUpgradeTest extends UpgradeTestBase
TopicSubscriber subscriber = session.createDurableSubscriber(topic, SUB_NAME);
Message migrated = subscriber.receive(getReceiveTimeout());
- assertThat("Failed to receive migrated message", migrated, is(notNullValue()));
+ assertNotNull(migrated, "Failed to receive migrated message");
Message receivedA = subscriber.receive(getReceiveTimeout());
session.commit();
- assertThat("Failed to receive published message A", receivedA, is(notNullValue()));
- assertThat("Message A is not Text message", receivedA, is(instanceOf(TextMessage.class)));
- assertThat("Unexpected text for A", ((TextMessage) receivedA).getText(), is(equalTo("A")));
- assertThat("Unexpected index", receivedA.getIntProperty("ID"), is(equalTo(index)));
+ assertNotNull(receivedA, "Failed to receive published message A");
+ assertTrue(receivedA instanceof TextMessage, "Message A is not Text message");
+ assertEquals(((TextMessage) receivedA).getText(),"A", "Unexpected text for A");
+ assertEquals(receivedA.getIntProperty("ID"), index, "Unexpected index");
Message receivedB = subscriber.receive(getReceiveTimeout());
session.commit();
- assertThat("Failed to receive published message B", receivedB, is(notNullValue()));
- assertThat("Message B is not Text message", receivedB, is(instanceOf(TextMessage.class)));
- assertThat("Unexpected text for B", ((TextMessage) receivedB).getText(), is(equalTo("B")));
- assertThat("Unexpected index for B", receivedB.getIntProperty("ID"), is(equalTo(index)));
+ assertNotNull(receivedB, "Failed to receive published message B");
+ assertTrue(receivedB instanceof TextMessage, "Message B is not Text message");
+ assertEquals(((TextMessage) receivedB).getText(), "B", "Unexpected text for B");
+ assertEquals(receivedB.getIntProperty("ID"), index, "Unexpected index for B");
session.commit();
session.close();
@@ -208,20 +208,15 @@ public class BDBUpgradeTest extends UpgradeTestBase
public void testQueueExclusivity() throws Exception
{
Map<String, Object> result = getQueueAttributes(QUEUE_NAME);
- assertThat("Exclusive policy attribute is not found",
- result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE),
- is(notNullValue()));
- assertThat("Queue should not have been marked as Exclusive during upgrade",
- ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
- is(equalTo(ExclusivityPolicy.NONE)));
+ assertNotNull(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE), "Exclusive policy attribute is not found");
+ assertEquals(ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
+ ExclusivityPolicy.NONE, "Queue should not have been marked as Exclusive during upgrade");
result = getQueueAttributes("clientid" + ":" + SUB_NAME);
- assertThat("Exclusive policy attribute is not found",
- result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE),
- is(notNullValue()));
- assertThat("DurableSubscription backing queue should have been marked as Exclusive during upgrade",
- ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
- is(not(equalTo(ExclusivityPolicy.NONE))));
+ assertNotNull(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE), "Exclusive policy attribute is not found");
+ assertNotEquals(ExclusivityPolicy.valueOf(String.valueOf(result.get(org.apache.qpid.server.model.Queue.EXCLUSIVE))),
+ ExclusivityPolicy.NONE,
+ "DurableSubscription backing queue should have been marked as Exclusive during upgrade");
}
/**
@@ -313,14 +308,14 @@ public class BDBUpgradeTest extends UpgradeTestBase
MessageConsumer consumer = session.createConsumer(queue);
Message message1 = consumer.receive(getReceiveTimeout());
- assertThat("expected message was not received", message1, is(instanceOf(TextMessage.class)));
- assertThat(((TextMessage) message1).getText(), is(equalTo("C")));
+ assertTrue(message1 instanceof TextMessage, "expected message was not received");
+ assertEquals(((TextMessage) message1).getText(), "C");
Message message2 = consumer.receive(getReceiveTimeout());
- assertThat("expected message was not received", message2, is(instanceOf(TextMessage.class)));
- assertThat(((TextMessage) message2).getText(), is(equalTo("A")));
+ assertTrue(message2 instanceof TextMessage, "expected message was not received");
+ assertEquals(((TextMessage) message2).getText(), "A");
Message message3 = consumer.receive(getReceiveTimeout());
- assertThat("expected message was not received", message3, is(instanceOf(TextMessage.class)));
- assertThat(((TextMessage) message3).getText(), is(equalTo("B")));
+ assertTrue(message3 instanceof TextMessage, "expected message was not received");
+ assertEquals(((TextMessage) message3).getText(), "B");
}
finally
{
@@ -341,39 +336,35 @@ public class BDBUpgradeTest extends UpgradeTestBase
{
//verify the DLE exchange exists, has the expected type, and a single binding for the DLQ
Map<String, Object> exchangeAttributes = getExchangeAttributes(QUEUE_WITH_DLQ_NAME + "_DLE");
- assertThat("Wrong exchange type",
- exchangeAttributes.get(Exchange.TYPE),
- is(equalTo("org.apache.qpid.FanoutExchange")));
+ assertEquals(exchangeAttributes.get(Exchange.TYPE), "org.apache.qpid.FanoutExchange", "Wrong exchange type");
@SuppressWarnings("unchecked")
Collection<Map<String, Object>> bindings = (Collection<Map<String, Object>>) exchangeAttributes.get("bindings");
- assertThat(bindings.size(), is(equalTo(1)));
+ assertEquals(bindings.size(), 1);
for (Map<String, Object> binding : bindings)
{
String bindingKey = (String) binding.get("bindingKey");
String queueName = (String) binding.get("destination");
//Because its a fanout exchange, we just return a single '*' key with all bound queues
- assertThat("unexpected binding key", bindingKey, is(equalTo("dlq")));
- assertThat("unexpected queue name", queueName, is(equalTo(QUEUE_WITH_DLQ_NAME + "_DLQ")));
+ assertEquals(bindingKey, "dlq", "unexpected binding key");
+ assertEquals(queueName, QUEUE_WITH_DLQ_NAME + "_DLQ", "unexpected queue name");
}
//verify the queue exists, has the expected alternate exchange and max delivery count
Map<String, Object> queueAttributes = getQueueAttributes(QUEUE_WITH_DLQ_NAME);
- assertThat("Queue does not have the expected AlternateExchange",
- queueAttributes.get(Exchange.ALTERNATE_BINDING),
- is(equalTo(Collections.singletonMap(AlternateBinding.DESTINATION, QUEUE_WITH_DLQ_NAME + "_DLE"))));
+ assertEquals(queueAttributes.get(Exchange.ALTERNATE_BINDING),
+ Collections.singletonMap(AlternateBinding.DESTINATION, QUEUE_WITH_DLQ_NAME + "_DLE"),
+ "Queue does not have the expected AlternateExchange");
- assertThat("Unexpected maximum delivery count",
- ((Number) queueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
- is(equalTo(2)));
+ assertEquals(((Number) queueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
+ 2, "Unexpected maximum delivery count");
Map<String, Object> dlQueueAttributes = getQueueAttributes(QUEUE_WITH_DLQ_NAME + "_DLQ");
- assertThat("Queue should not have an AlternateExchange",
- dlQueueAttributes.get(org.apache.qpid.server.model.Queue.ALTERNATE_BINDING), is(nullValue()));
- assertThat("Unexpected maximum delivery count",
- ((Number) dlQueueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
- is(equalTo(0)));
+ assertNull(dlQueueAttributes.get(org.apache.qpid.server.model.Queue.ALTERNATE_BINDING),
+ "Queue should not have an AlternateExchange");
+ assertEquals(((Number) dlQueueAttributes.get(org.apache.qpid.server.model.Queue.MAXIMUM_DELIVERY_ATTEMPTS)).intValue(),
+ 0, "Unexpected maximum delivery count");
try
{
@@ -383,7 +374,7 @@ public class BDBUpgradeTest extends UpgradeTestBase
}
catch (AmqpManagementFacade.OperationUnsuccessfulException e)
{
- assertThat(e.getStatusCode(), is(equalTo(404)));
+ assertEquals(e.getStatusCode(), 404);
}
}
@@ -406,8 +397,8 @@ public class BDBUpgradeTest extends UpgradeTestBase
private void consumeDurableSubscriptionMessages(Connection connection, boolean selector) throws Exception
{
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Topic topic = null;
- TopicSubscriber durSub = null;
+ Topic topic;
+ TopicSubscriber durSub;
if (selector)
{
@@ -422,19 +413,17 @@ public class BDBUpgradeTest extends UpgradeTestBase
// Retrieve the matching message
Message m = durSub.receive(getReceiveTimeout());
- assertThat("Failed to receive an expected message", m, is(notNullValue()));
+ assertNotNull(m, "Failed to receive an expected message");
if (selector)
{
- assertThat("Selector property did not match", m.getStringProperty("testprop"), is(equalTo("true")));
+ assertEquals(m.getStringProperty("testprop"), "true", "Selector property did not match");
}
- assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(1)));
- assertThat("Message content was not as expected",
- ((TextMessage) m).getText(),
- is(equalTo(generateString(1024))));
+ assertEquals(m.getIntProperty("ID"), 1, "ID property did not match");
+ assertEquals(((TextMessage) m).getText(), generateString(1024), "Message content was not as expected");
// Verify that no more messages are received
m = durSub.receive(getReceiveTimeout());
- assertThat("No more messages should have been recieved", m, is(nullValue()));
+ assertNull(m, "No more messages should have been recieved");
durSub.close();
session.close();
@@ -452,32 +441,30 @@ public class BDBUpgradeTest extends UpgradeTestBase
for (int i = 1; i <= 5; i++)
{
m = consumer.receive(getReceiveTimeout());
- assertThat("Failed to receive an expected message", m, is(notNullValue()));
- assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(i)));
- assertThat("Message content was not as expected",
- ((TextMessage) m).getText(),
- is(equalTo(STRING_1024_256)));
+ assertNotNull(m, "Failed to receive an expected message");
+ assertEquals(m.getIntProperty("ID"), i, "ID property did not match");
+ assertEquals(((TextMessage) m).getText(), STRING_1024_256, "Message content was not as expected");
}
for (int i = 1; i <= 5; i++)
{
m = consumer.receive(getReceiveTimeout());
- assertThat("Failed to receive an expected message", m, is(notNullValue()));
- assertThat("ID property did not match", m.getIntProperty("ID"), is(equalTo(i)));
- assertThat("Message content was not as expected", ((TextMessage) m).getText(), is((equalTo(STRING_1024))));
+ assertNotNull(m, "Failed to receive an expected message");
+ assertEquals(m.getIntProperty("ID"), i, "ID property did not match");
+ assertEquals(((TextMessage) m).getText(), STRING_1024, "Message content was not as expected");
}
if (extraMessage)
{
//verify that the extra message is received
m = consumer.receive(getReceiveTimeout());
- assertThat("Failed to receive an expected message", m, is(notNullValue()));
- assertThat("ID property did not match", m.getIntProperty(INDEX), is(equalTo(0)));
+ assertNotNull(m, "Failed to receive an expected message");
+ assertEquals(m.getIntProperty(INDEX), 0, "ID property did not match");
}
else
{
// Verify that no more messages are received
m = consumer.receive(getReceiveTimeout());
- assertThat("No more messages should have been recieved", m, is(nullValue()));
+ assertNull(m, "No more messages should have been recieved");
}
consumer.close();
@@ -500,5 +487,4 @@ public class BDBUpgradeTest extends UpgradeTestBase
}
return new String(chars);
}
-
}
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
index ae2d373a66..7ae7b65e57 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/UpgradeTestBase.java
@@ -20,7 +20,7 @@
*/
package org.apache.qpid.server.store.berkeleydb;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.IOException;
@@ -30,7 +30,7 @@ import java.util.Map;
import javax.jms.Connection;
-import org.junit.Before;
+import org.junit.jupiter.api.BeforeEach;
import org.apache.qpid.server.util.FileUtils;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode;
@@ -38,7 +38,7 @@ import org.apache.qpid.systests.JmsTestBase;
public abstract class UpgradeTestBase extends JmsTestBase
{
- @Before
+ @BeforeEach
public void restartWithOldStore() throws Exception
{
Connection connection = getConnectionBuilder().setVirtualHost("$management").build();
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
index 59900d3936..f9d27194af 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/GroupJmsTestBase.java
@@ -23,7 +23,7 @@ package org.apache.qpid.server.store.berkeleydb.replication;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assume.assumeThat;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.concurrent.atomic.AtomicReference;
@@ -32,12 +32,13 @@ import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.Session;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.rules.ExternalResource;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.extension.BeforeAllCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,57 +53,48 @@ public class GroupJmsTestBase extends UnitTestBase
private static final int FAILOVER_CONNECTDELAY = 1000;
static final int SHORT_FAILOVER_CYCLECOUNT = 2;
static final int SHORT_FAILOVER_CONNECTDELAY = 200;
- private static final AtomicReference<Class<?>> TEST_CLASS = new AtomicReference<>();
- private static final Logger LOGGER = LoggerFactory.getLogger(GroupJmsTestBase.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(GroupJmsTestBase.class);
private static JmsProvider _jmsProvider;
private static GroupBrokerAdmin _groupBrokerAdmin;
+ private static AtomicReference<Class<?>> _testClass = new AtomicReference<>();
- @BeforeClass
+ @BeforeAll
public static void setUpTestBase()
{
- assumeThat(System.getProperty("virtualhostnode.type", "BDB"), is(equalTo("BDB")));
+ assumeTrue("BDB".equals(System.getProperty("virtualhostnode.type", "BDB")),
+ "VirtualHostNodeStoreType should be BDB");
_jmsProvider = Utils.getJmsProvider();
}
- @AfterClass
+ @AfterAll
public static void tearDownTestBase()
{
- Class<?> testClass = TEST_CLASS.get();
- if (testClass != null && TEST_CLASS.compareAndSet(testClass, null))
+ Class<?> testClass = _testClass.get();
+ if (testClass != null && _testClass.compareAndSet(testClass, null))
{
_groupBrokerAdmin.afterTestClass(testClass);
}
}
- @Rule
- public final ExternalResource resource = new ExternalResource()
+ @RegisterExtension
+ public final BeforeAllCallback resource = (ExtensionContext ctx) ->
{
- @Override
- protected void before()
- {
- if (TEST_CLASS.compareAndSet(null, GroupJmsTestBase.this.getClass()))
- {
- _groupBrokerAdmin = new GroupBrokerAdmin();
- _groupBrokerAdmin.beforeTestClass(GroupJmsTestBase.this.getClass());
- }
- }
-
- @Override
- protected void after()
+ if (_testClass.compareAndSet(null, GroupJmsTestBase.this.getClass() ))
{
-
+ _groupBrokerAdmin = new GroupBrokerAdmin();
+ _groupBrokerAdmin.beforeTestClass(GroupJmsTestBase.this.getClass());
}
};
- @Before
+ @BeforeEach
public void beforeTestMethod() throws Exception
{
_groupBrokerAdmin.beforeTestMethod(getClass(), getClass().getMethod(getTestName()));
}
- @After
+ @AfterEach
public void afterTestMethod() throws Exception
{
_groupBrokerAdmin.afterTestMethod(getClass(), getClass().getMethod(getTestName()));
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
index 91f8b45c73..35d6f6f4c4 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/MultiNodeTest.java
@@ -19,17 +19,13 @@
*/
package org.apache.qpid.server.store.berkeleydb.replication;
-import static junit.framework.TestCase.assertEquals;
import static org.apache.qpid.systests.Utils.INDEX;
import static org.apache.qpid.systests.Utils.getReceiveTimeout;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertNotNull;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.net.URI;
@@ -60,11 +56,12 @@ import javax.jms.TextMessage;
import javax.jms.TransactionRolledBackException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Objects;
import com.sleepycat.je.Durability;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.ReplicationConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -87,7 +84,6 @@ public class MultiNodeTest extends GroupJmsTestBase
{
private static final Logger LOGGER = LoggerFactory.getLogger(MultiNodeTest.class);
-
private FailoverAwaitingListener _failoverListener = new FailoverAwaitingListener();
private static final int FAILOVER_COMPLETION_TIMEOUT = 60000;
@@ -271,8 +267,8 @@ public class MultiNodeTest extends GroupJmsTestBase
for (int i = 0; i < 10; i++)
{
Message m = consumer.receive(getReceiveTimeout());
- assertNotNull("Message " + i + " is not received", m);
- assertEquals("Unexpected message received", i, m.getIntProperty(INDEX));
+ assertNotNull(m, "Message " + i + " is not received");
+ assertEquals(i, m.getIntProperty(INDEX), "Unexpected message received");
}
consumingSession.commit();
}
@@ -315,7 +311,7 @@ public class MultiNodeTest extends GroupJmsTestBase
{
transferMasterToNodeWithAmqpPort(connection, inactiveBrokerPort);
- assertThat(Utils.produceConsume(connection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(connection, queue), "Message should be produced and consumed");
getBrokerAdmin().awaitNodeRole(activeBrokerPort, "REPLICA");
}
@@ -327,15 +323,16 @@ public class MultiNodeTest extends GroupJmsTestBase
getJmsProvider().addGenericConnectionListener(connection, _failoverListener);
Map<String, Object> attributes = getBrokerAdmin().getNodeAttributes(nodeAmqpPort);
- assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
- getBrokerAdmin().setNodeAttributes(nodeAmqpPort,
- Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
+ assertEquals("REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "Inactive broker has unexpected role");
+ getBrokerAdmin().setNodeAttributes(nodeAmqpPort, Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
_failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Listener has finished");
attributes = getBrokerAdmin().getNodeAttributes(nodeAmqpPort);
- assertEquals("Inactive broker has unexpected role", "MASTER", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("MASTER", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "Inactive broker has unexpected role");
}
@Test
@@ -373,7 +370,8 @@ public class MultiNodeTest extends GroupJmsTestBase
getBrokerAdmin().awaitRemoteNodeRole(activeBrokerPort, inactiveBrokerPort, "REPLICA");
Map<String, Object> attributes = getBrokerAdmin().getRemoteNodeAttributes(activeBrokerPort, inactiveBrokerPort);
- assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "Inactive broker has unexpected role");
getBrokerAdmin().setRemoteNodeAttributes(activeBrokerPort,
inactiveBrokerPort,
@@ -383,9 +381,9 @@ public class MultiNodeTest extends GroupJmsTestBase
LOGGER.info("Listener has finished");
attributes = getBrokerAdmin().getNodeAttributes(inactiveBrokerPort);
- assertEquals("Inactive broker has unexpected role", "MASTER", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("MASTER", attributes.get(BDBHAVirtualHostNode.ROLE), "Inactive broker has unexpected role");
- assertThat(Utils.produceConsume(connection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(connection, queue), "Message should be produced and consumed");
getBrokerAdmin().awaitNodeRole(activeBrokerPort, "REPLICA");
}
@@ -471,7 +469,8 @@ public class MultiNodeTest extends GroupJmsTestBase
getBrokerAdmin().awaitNodeRole(inactiveBrokerPort, "REPLICA");
Map<String, Object> attributes = getBrokerAdmin().getNodeAttributes(inactiveBrokerPort);
- assertEquals("Inactive broker has unexpected role", "REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("REPLICA", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "Inactive broker has unexpected role");
getBrokerAdmin().setNodeAttributes(inactiveBrokerPort,
Collections.singletonMap(BDBHAVirtualHostNode.ROLE, "MASTER"));
@@ -480,7 +479,8 @@ public class MultiNodeTest extends GroupJmsTestBase
LOGGER.info("Failover has finished");
attributes = getBrokerAdmin().getNodeAttributes(inactiveBrokerPort);
- assertEquals("New master has unexpected role", "MASTER", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("MASTER", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "New master has unexpected role");
getBrokerAdmin().awaitNodeRole(activeBrokerPort, "REPLICA");
@@ -488,14 +488,15 @@ public class MultiNodeTest extends GroupJmsTestBase
masterTransferred.set(true);
boolean producedMore = producedOneAfter.await(5000, TimeUnit.MILLISECONDS);
- assertTrue("Should have successfully produced at least one message after transfer complete", producedMore);
+ assertTrue(producedMore, "Should have successfully produced at least one message after transfer complete");
keepRunning.set(false);
boolean shutdown = workerShutdown.await(5000, TimeUnit.MILLISECONDS);
- assertTrue("Worker thread should have shutdown", shutdown);
+ assertTrue(shutdown, "Worker thread should have shutdown");
backgroundWorker.join(5000);
- assertThat(workerException.get(), is(nullValue()));
+
+ assumeTrue(workerException.get() == null,"Exception shouldn't be thrown");
assertNotNull(session.createTemporaryQueue());
}
@@ -717,21 +718,19 @@ public class MultiNodeTest extends GroupJmsTestBase
LOGGER.info("Failover has begun");
Map<String, Object> attributes = getBrokerAdmin().getNodeAttributes(activeBrokerPort);
- assertEquals("Broker has unexpected quorum override",
- Integer.valueOf(0),
- attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE));
+ assertEquals(0, attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE),
+ "Broker has unexpected quorum override");
getBrokerAdmin().setNodeAttributes(activeBrokerPort,
Collections.singletonMap(BDBHAVirtualHostNode.QUORUM_OVERRIDE, 1));
attributes = getBrokerAdmin().getNodeAttributes(activeBrokerPort);
- assertEquals("Broker has unexpected quorum override",
- Integer.valueOf(1),
- attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE));
+ assertEquals(1, attributes.get(BDBHAVirtualHostNode.QUORUM_OVERRIDE),
+ "Broker has unexpected quorum override");
_failoverListener.awaitFailoverCompletion(FAILOVER_COMPLETION_TIMEOUT);
LOGGER.info("Failover has finished");
- assertThat(Utils.produceConsume(connection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(connection, queue),"Message should be produced and consumed");
}
finally
{
@@ -765,9 +764,8 @@ public class MultiNodeTest extends GroupJmsTestBase
Collections.singletonMap(BDBHAVirtualHostNode.PRIORITY,
priority));
Map<String, Object> attributes = getBrokerAdmin().getNodeAttributes(port);
- assertEquals("Broker has unexpected priority",
- priority,
- attributes.get(BDBHAVirtualHostNode.PRIORITY));
+ assertEquals(priority,attributes.get(BDBHAVirtualHostNode.PRIORITY),
+ "Broker has unexpected priority");
}
}
@@ -782,13 +780,13 @@ public class MultiNodeTest extends GroupJmsTestBase
}
// do work on master
- assertThat(Utils.produceConsume(connection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(connection, queue),"Message should be produced and consumed");
Map<String, Object> masterNodeAttributes = getBrokerAdmin().getNodeAttributes(activeBrokerPort);
Object lastTransactionId =
masterNodeAttributes.get(BDBHAVirtualHostNode.LAST_KNOWN_REPLICATION_TRANSACTION_ID);
- assertTrue("Unexpected last transaction id: " + lastTransactionId, lastTransactionId instanceof Number);
+ assertTrue(lastTransactionId instanceof Number, "Unexpected last transaction id: " + lastTransactionId);
// make sure all remote nodes have the same transaction id as master
for (Integer port : ports)
@@ -809,9 +807,10 @@ public class MultiNodeTest extends GroupJmsTestBase
Map<String, Object> attributes =
getBrokerAdmin().getNodeAttributes(highestPriorityBrokerPort);
- assertEquals("Inactive broker has unexpected role", "MASTER", attributes.get(BDBHAVirtualHostNode.ROLE));
+ assertEquals("MASTER", attributes.get(BDBHAVirtualHostNode.ROLE),
+ "Inactive broker has unexpected role");
- assertThat(Utils.produceConsume(connection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(connection, queue),"Message should be produced and consumed");
}
finally
{
@@ -946,8 +945,8 @@ public class MultiNodeTest extends GroupJmsTestBase
for (String m : expected)
{
final Message message = consumer.receive(getReceiveTimeout());
- assertThat(message, is(instanceOf(TextMessage.class)));
- assertThat(((TextMessage) message).getText(), is(equalTo(m)));
+ assumeTrue(message instanceof TextMessage,"Message should be a text message");
+ assumeTrue(Objects.equal(m, ((TextMessage) message).getText()),"Message text should be " + m);
}
}
finally
@@ -997,19 +996,19 @@ public class MultiNodeTest extends GroupJmsTestBase
LOGGER.warn("Broker {} thread dump:\n\n {}", entry.getKey(), entry.getValue());
}
}
- assertEquals("Failover did not occur", 0, _failoverCompletionLatch.getCount());
+ assertEquals(0, _failoverCompletionLatch.getCount(), "Failover did not occur");
}
void assertNoFailoverCompletionWithin(long delay) throws InterruptedException
{
_failoverCompletionLatch.await(delay, TimeUnit.MILLISECONDS);
- assertEquals("Failover occurred unexpectedly", 1L, _failoverCompletionLatch.getCount());
+ assertEquals(1L, _failoverCompletionLatch.getCount(), "Failover occurred unexpectedly");
}
void awaitPreFailover(long delay) throws InterruptedException
{
boolean complete = _preFailoverLatch.await(delay, TimeUnit.MILLISECONDS);
- assertTrue("Failover was expected to begin within " + delay + " ms.", complete);
+ assertTrue(complete, "Failover was expected to begin within " + delay + " ms.");
}
synchronized boolean isFailoverStarted()
diff --git a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
index 5d7086f58f..a27e0b0358 100644
--- a/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
+++ b/bdbstore/systests/src/test/java/org/apache/qpid/server/store/berkeleydb/replication/TwoNodeTest.java
@@ -19,10 +19,8 @@
*/
package org.apache.qpid.server.store.berkeleydb.replication;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.Map;
@@ -30,7 +28,7 @@ import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Queue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBHAVirtualHostNode;
import org.apache.qpid.systests.Utils;
@@ -69,7 +67,8 @@ public class TwoNodeTest extends GroupJmsTestBase
try
{
queue = createTestQueue(initialConnection);
- assertThat(Utils.produceConsume(initialConnection, queue), is(equalTo(true)));
+ assumeTrue(Utils.produceConsume(initialConnection, queue),
+ "Messages should be produced and consumed");
}
finally
{
@@ -187,14 +186,14 @@ public class TwoNodeTest extends GroupJmsTestBase
Map<String, Object>
primaryNodeAttributes = getBrokerAdmin().getNodeAttributes(masterPort);
- assertThat("Expected primary node to be set as designated primary",
- primaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY), is(equalTo(true)));
+ assumeTrue(Boolean.TRUE.equals(primaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY)),
+ "Expected primary node to be set as designated primary");
int replicaPort = getBrokerAdmin().getAmqpPort(masterPort);
Map<String, Object> secondaryNodeAttributes = getBrokerAdmin().getNodeAttributes(replicaPort);
- assertThat("Expected secondary node to NOT be set as designated primary",
- secondaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY), is(equalTo(false)));
+ assumeTrue(Boolean.FALSE.equals(secondaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY)),
+ "Expected secondary node to NOT be set as designated primary");
}
@Test
@@ -219,9 +218,8 @@ public class TwoNodeTest extends GroupJmsTestBase
int replicaPort = getBrokerAdmin().getAmqpPort(masterPort);
Map<String, Object> secondaryNodeAttributes = getBrokerAdmin().getNodeAttributes(replicaPort);
- assertThat("Expected secondary node to NOT be set as designated primary",
- secondaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY), is(equalTo(false)));
-
+ assumeTrue(Boolean.FALSE.equals(secondaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY)),
+ "Expected secondary node to NOT be set as designated primary");
getBrokerAdmin().setDesignatedPrimary(replicaPort, true);
getBrokerAdmin().awaitNodeRole(replicaPort, "MASTER");
@@ -249,9 +247,8 @@ public class TwoNodeTest extends GroupJmsTestBase
Map<String, Object>
primaryNodeAttributes = getBrokerAdmin().getNodeAttributes(masterPort);
- assertThat("Expected node to NOT be set as designated primary",
- primaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY), is(equalTo(false)));
-
+ assumeTrue(Boolean.FALSE.equals(primaryNodeAttributes.get(BDBHAVirtualHostNode.DESIGNATED_PRIMARY)),
+ "Expected node to NOT be set as designated primary");
getBrokerAdmin().setDesignatedPrimary(masterPort, true);
getBrokerAdmin().awaitNodeRole(masterPort, "MASTER");
diff --git a/broker-core/pom.xml b/broker-core/pom.xml
index 527fdc4225..873405b3ec 100644
--- a/broker-core/pom.xml
+++ b/broker-core/pom.xml
@@ -80,78 +80,18 @@
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core-annotations</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core-api</artifactId>
- <scope>test</scope>
- </dependency>
-
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-interceptor-kerberos</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-kerberos-codec</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-kerberos</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-ldap</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-shared</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-annotations</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-config</artifactId>
- <scope>test</scope>
- </dependency>
-
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-test-framework</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.kerby</groupId>
- <artifactId>kerb-simplekdc</artifactId>
- <scope>test</scope>
- </dependency>
-
</dependencies>
<build>
diff --git a/broker-core/src/test/java/org/apache/qpid/server/SelectorParserTest.java b/broker-core/src/test/java/org/apache/qpid/server/SelectorParserTest.java
index 313d468250..075df0eec7 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/SelectorParserTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/SelectorParserTest.java
@@ -21,12 +21,12 @@
package org.apache.qpid.server;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.filter.JMSSelectorFilter;
-import org.apache.qpid.server.filter.SelectorParsingException;
import org.apache.qpid.server.filter.selector.ParseException;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -63,7 +63,6 @@ public class SelectorParserTest extends UnitTestBase
testFail("prop1 = prop2 foo AND string = 'Test'");
}
-
@Test
public void testPropertyNames()
{
@@ -86,7 +85,6 @@ public class SelectorParserTest extends UnitTestBase
testFail("ESCAPE = 0 ");
}
-
@Test
public void testBoolean()
{
@@ -125,38 +123,13 @@ public class SelectorParserTest extends UnitTestBase
testPass("octal=042");
}
-
- private void testPass(String selector)
+ private void testPass(final String selector)
{
- try
- {
- new JMSSelectorFilter(selector);
- }
- catch (ParseException e)
- {
- fail("Selector '" + selector + "' was not parsed :" + e.getMessage());
- }
- catch (SelectorParsingException e)
- {
- fail("Selector '" + selector + "' was not parsed :" + e.getMessage());
- }
+ assertDoesNotThrow(() -> new JMSSelectorFilter(selector), "Selector '" + selector + "' was not parsed");
}
- private void testFail(String selector)
+ private void testFail(final String selector)
{
- try
- {
- new JMSSelectorFilter(selector);
- fail("Selector '" + selector + "' was parsed ");
- }
- catch (ParseException e)
- {
- //normal path
- }
- catch (SelectorParsingException e)
- {
- //normal path
- }
+ assertThrows(Exception.class, () -> new JMSSelectorFilter(selector), "Selector '" + selector + "' was parsed");
}
-
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/SystemLauncherTest.java b/broker-core/src/test/java/org/apache/qpid/server/SystemLauncherTest.java
index d7f9a58615..b0b4b10838 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/SystemLauncherTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/SystemLauncherTest.java
@@ -20,21 +20,20 @@
*/
package org.apache.qpid.server;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
-import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.logging.messages.BrokerMessages;
import org.apache.qpid.server.model.BrokerModel;
@@ -55,17 +54,16 @@ public class SystemLauncherTest extends UnitTestBase
private File _brokerWork;
private SystemLauncher _systemLauncher;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
// create empty initial configuration
- Map<String,Object> initialConfig = new HashMap<>();
- initialConfig.put(ConfiguredObject.NAME, "test");
- initialConfig.put(org.apache.qpid.server.model.Broker.MODEL_VERSION, BrokerModel.MODEL_VERSION);
+ final Map<String,Object> initialConfig = Map.of(ConfiguredObject.NAME, "test",
+ org.apache.qpid.server.model.Broker.MODEL_VERSION, BrokerModel.MODEL_VERSION);
- ObjectMapper mapper = new ObjectMapper();
- String config = mapper.writeValueAsString(initialConfig);
+ final ObjectMapper mapper = new ObjectMapper();
+ final String config = mapper.writeValueAsString(initialConfig);
_initialConfiguration = TestFileUtils.createTempFile(this, ".initial-config.json", config);
_brokerWork = TestFileUtils.createTestDirectory("qpid-work", true);
_initialSystemProperties = TestFileUtils.createTempFile(this, ".initial-system.properties",
@@ -74,86 +72,77 @@ public class SystemLauncherTest extends UnitTestBase
setTestSystemProperty("QPID_WORK", _brokerWork.getAbsolutePath());
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
- try
- {
- }
- finally
+ if (_systemLauncher != null)
{
- if (_systemLauncher != null)
- {
- _systemLauncher.shutdown();
- }
- System.clearProperty(INITIAL_SYSTEM_PROPERTY);
- FileUtils.delete(_brokerWork, true);
- FileUtils.delete(_initialSystemProperties, false);
- FileUtils.delete(_initialConfiguration, false);
+ _systemLauncher.shutdown();
}
+ System.clearProperty(INITIAL_SYSTEM_PROPERTY);
+ FileUtils.delete(_brokerWork, true);
+ FileUtils.delete(_initialSystemProperties, false);
+ FileUtils.delete(_initialConfiguration, false);
}
@Test
public void testInitialSystemPropertiesAreSetOnBrokerStartup() throws Exception
{
- Map<String,Object> attributes = new HashMap<>();
- attributes.put(SystemConfig.INITIAL_SYSTEM_PROPERTIES_LOCATION, _initialSystemProperties.getAbsolutePath());
- attributes.put(SystemConfig.INITIAL_CONFIGURATION_LOCATION, _initialConfiguration.getAbsolutePath());
- attributes.put(SystemConfig.TYPE, JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE);
- attributes.put(SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, Boolean.TRUE);
+ final Map<String,Object> attributes = Map.of(SystemConfig.INITIAL_SYSTEM_PROPERTIES_LOCATION, _initialSystemProperties.getAbsolutePath(),
+ SystemConfig.INITIAL_CONFIGURATION_LOCATION, _initialConfiguration.getAbsolutePath(),
+ SystemConfig.TYPE, JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE,
+ SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, Boolean.TRUE);
_systemLauncher = new SystemLauncher();
_systemLauncher.startup(attributes);
// test JVM system property should be set from initial system config file
- assertEquals("Unexpected JVM system property",
- INITIAL_SYSTEM_PROPERTY_VALUE,
- System.getProperty(INITIAL_SYSTEM_PROPERTY));
+ assertEquals(INITIAL_SYSTEM_PROPERTY_VALUE, System.getProperty(INITIAL_SYSTEM_PROPERTY),
+ "Unexpected JVM system property");
// existing system property should not be overridden
- assertEquals("Unexpected QPID_WORK system property",
- _brokerWork.getAbsolutePath(),
- System.getProperty("QPID_WORK"));
+ assertEquals(_brokerWork.getAbsolutePath(), System.getProperty("QPID_WORK"),
+ "Unexpected QPID_WORK system property");
}
@Test
public void testConsoleLogsOnSuccessfulStartup() throws Exception
{
- byte[] outputBytes = startBrokerAndCollectSystemOutput();
- String output = new String(outputBytes);
- assertFalse("Detected unexpected Exception: " + output, output.contains("Exception"));
- assertTrue("Output does not contain Broker Ready Message",
- output.contains(BrokerMessages.READY().toString()));
+ final byte[] outputBytes = startBrokerAndCollectSystemOutput();
+ final String output = new String(outputBytes);
+ assertFalse(output.contains("Exception"), "Detected unexpected Exception: " + output);
+ assertTrue(output.contains(BrokerMessages.READY().toString()),
+ "Output does not contain Broker Ready Message");
}
@Test
public void testConsoleLogsOnUnsuccessfulStartup() throws Exception
{
- Map<String,Object> initialConfig = new HashMap<>();
+ final Map<String,Object> initialConfig = Map.of();
- ObjectMapper mapper = new ObjectMapper();
- String config = mapper.writeValueAsString(initialConfig);
+ final ObjectMapper mapper = new ObjectMapper();
+ final String config = mapper.writeValueAsString(initialConfig);
TestFileUtils.saveTextContentInFile(config, _initialConfiguration);
- byte[] outputBytes = startBrokerAndCollectSystemOutput();
- String output = new String(outputBytes);
- assertTrue("No Exception detected in output: " + output, output.contains("Exception"));
- assertFalse("Output contains Broker Ready Message", output.contains(BrokerMessages.READY().toString()));
+ final byte[] outputBytes = startBrokerAndCollectSystemOutput();
+ final String output = new String(outputBytes);
+ assertTrue(output.contains("Exception"), "No Exception detected in output: " + output);
+ assertFalse(output.contains(BrokerMessages.READY().toString()),
+ "Output contains Broker Ready Message");
}
private byte[] startBrokerAndCollectSystemOutput() throws Exception
{
- try(ByteArrayOutputStream out = new ByteArrayOutputStream())
+ try (final ByteArrayOutputStream out = new ByteArrayOutputStream())
{
- PrintStream originalOutput = System.out;
+ final PrintStream originalOutput = System.out;
try
{
System.setOut(new PrintStream(out));
- Map<String,Object> attributes = new HashMap<>();
- attributes.put(SystemConfig.INITIAL_CONFIGURATION_LOCATION, _initialConfiguration.getAbsolutePath());
- attributes.put(SystemConfig.TYPE, JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE);
+ final Map<String,Object> attributes = Map.of(SystemConfig.INITIAL_CONFIGURATION_LOCATION, _initialConfiguration.getAbsolutePath(),
+ SystemConfig.TYPE, JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE);
_systemLauncher = new SystemLauncher();
_systemLauncher.startup(attributes);
@@ -162,9 +151,7 @@ public class SystemLauncherTest extends UnitTestBase
{
System.setOut(originalOutput);
}
-
return out.toByteArray();
}
-
}
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
index f90f373397..1064147a5a 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
@@ -21,14 +21,14 @@
package org.apache.qpid.server.bytebuffer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -38,34 +38,27 @@ public class QpidByteBufferOutputStreamTest extends UnitTestBase
private static final int POOL_SIZE = 20;
private static final double SPARSITY_FRACTION = 0.5;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
QpidByteBuffer.deinitialisePool();
QpidByteBuffer.initialisePool(BUFFER_SIZE, POOL_SIZE, SPARSITY_FRACTION);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
- try
- {
- }
- finally
- {
- QpidByteBuffer.deinitialisePool();
- }
+ QpidByteBuffer.deinitialisePool();
}
@Test
public void testWriteByteByByte() throws Exception
{
- boolean direct = false;
- try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
+ final boolean direct = false;
+ try (final QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
{
stream.write('a');
stream.write('b');
-
assertBufferContent(false, "ab".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
}
}
@@ -73,12 +66,11 @@ public class QpidByteBufferOutputStreamTest extends UnitTestBase
@Test
public void testWriteByteArrays() throws Exception
{
- boolean direct = false;
- try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
+ final boolean direct = false;
+ try (final QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
{
stream.write("abcd".getBytes(), 0, 4);
stream.write("_ef_".getBytes(), 1, 2);
-
assertBufferContent(direct, "abcdef".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
}
}
@@ -86,35 +78,32 @@ public class QpidByteBufferOutputStreamTest extends UnitTestBase
@Test
public void testWriteMixed() throws Exception
{
- boolean direct = true;
- try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
+ final boolean direct = true;
+ try (final QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
{
stream.write('a');
stream.write("bcd".getBytes());
-
assertBufferContent(direct, "abcd".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
}
}
-
@Test
public void testWriteByteArrays_ArrayTooLargeForSingleBuffer() throws Exception
{
- boolean direct = false;
- try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
+ final boolean direct = false;
+ try (final QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
{
stream.write("abcdefghi".getBytes());
-
assertBufferContent(direct, "abcdefghi".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
}
}
private void assertBufferContent(final boolean isDirect, final byte[] expected, final QpidByteBuffer buffer)
{
- assertEquals("Unexpected buffer type", isDirect, buffer.isDirect());
- byte[] buf = new byte[buffer.remaining()];
+ assertEquals(isDirect, buffer.isDirect(), "Unexpected buffer type");
+ final byte[] buf = new byte[buffer.remaining()];
buffer.get(buf);
buffer.dispose();
- Assert.assertArrayEquals("Unexpected buffer content", expected, buf);
+ assertArrayEquals(expected, buf, "Unexpected buffer content");
}
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
index 0bbbfd4a09..be2f8dded4 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
@@ -20,11 +20,13 @@
package org.apache.qpid.server.bytebuffer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -40,10 +42,10 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import com.google.common.io.ByteStreams;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.mockito.internal.util.Primitives;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -55,11 +57,10 @@ public class QpidByteBufferTest extends UnitTestBase
private static final int POOL_SIZE = 20;
private static final double SPARSITY_FRACTION = 0.5;
-
private QpidByteBuffer _slicedBuffer;
private QpidByteBuffer _parent;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
QpidByteBuffer.deinitialisePool();
@@ -67,24 +68,18 @@ public class QpidByteBufferTest extends UnitTestBase
_parent = QpidByteBuffer.allocateDirect(BUFFER_SIZE);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
- try
+ if (_parent != null)
{
+ _parent.dispose();
}
- finally
+ if (_slicedBuffer != null)
{
- if (_parent != null)
- {
- _parent.dispose();
- }
- if (_slicedBuffer != null)
- {
- _slicedBuffer.dispose();
- }
- QpidByteBuffer.deinitialisePool();
+ _slicedBuffer.dispose();
}
+ QpidByteBuffer.deinitialisePool();
}
@Test
@@ -109,27 +104,26 @@ public class QpidByteBufferTest extends UnitTestBase
testPutGet(char.class, false, 'A');
testPutGet(short.class, false, (short)1);
testPutGet(byte.class, false, (byte)1);
-
testPutGet(int.class, true, 1L);
testPutGet(short.class, true, 1);
testPutGet(byte.class, true, (short)1);
}
@Test
- public void testMarkReset() throws Exception
+ public void testMarkReset()
{
_slicedBuffer = createSlice();
_slicedBuffer.mark();
_slicedBuffer.position(_slicedBuffer.position() + 1);
- assertEquals("Unexpected position after move", (long) 1, (long) _slicedBuffer.position());
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position after move");
_slicedBuffer.reset();
- assertEquals("Unexpected position after reset", (long) 0, (long) _slicedBuffer.position());
+ assertEquals(0, (long) _slicedBuffer.position(), "Unexpected position after reset");
}
@Test
- public void testMarkResetAcrossFragmentBoundary() throws Exception
+ public void testMarkResetAcrossFragmentBoundary()
{
for (int i = 0; i < BUFFER_SIZE; ++i)
{
@@ -139,36 +133,29 @@ public class QpidByteBufferTest extends UnitTestBase
_parent.mark();
for (int i = 0; i < BUFFER_FRAGMENT_SIZE + 2; ++i)
{
- assertEquals("Unexpected value", (long) i, (long) _parent.get());
+ assertEquals(i, (long) _parent.get(), "Unexpected value");
}
_parent.reset();
for (int i = 0; i < BUFFER_SIZE; ++i)
{
- assertEquals("Unexpected value", (long) i, (long) _parent.get());
+ assertEquals(i, (long) _parent.get(), "Unexpected value");
}
}
@Test
- public void testPosition() throws Exception
+ public void testPosition()
{
_slicedBuffer = createSlice();
- assertEquals("Unexpected position for new slice", (long) 0, (long) _slicedBuffer.position());
+ assertEquals(0, (long) _slicedBuffer.position(), "Unexpected position for new slice");
_slicedBuffer.position(1);
- assertEquals("Unexpected position after advance", (long) 1, (long) _slicedBuffer.position());
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position after advance");
final int oldLimit = _slicedBuffer.limit();
_slicedBuffer.limit(oldLimit - 1);
- try
- {
- _slicedBuffer.position(oldLimit);
- fail("Exception not thrown");
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
+
+ assertThrows(IllegalArgumentException.class, () -> _slicedBuffer.position(oldLimit),"Exception not thrown");
}
@Test
@@ -177,15 +164,8 @@ public class QpidByteBufferTest extends UnitTestBase
_parent.position(8);
_parent.mark();
_parent.position(7);
- try
- {
- _parent.reset();
- fail("Expected exception not thrown");
- }
- catch (InvalidMarkException e)
- {
- // pass
- }
+
+ assertThrows(InvalidMarkException.class, () -> _parent.reset(), "Expected exception not thrown");
}
@Test
@@ -195,84 +175,60 @@ public class QpidByteBufferTest extends UnitTestBase
_parent.position(originalPosition);
_parent.mark();
_parent.position(9);
-
_parent.reset();
- assertEquals("Unexpected position", (long) originalPosition, (long) _parent.position());
+ assertEquals(originalPosition, (long) _parent.position(), "Unexpected position");
}
@Test
- public void testRewind() throws Exception
+ public void testRewind()
{
final int expectedLimit = 7;
_parent.position(1);
_parent.limit(expectedLimit);
_parent.mark();
_parent.position(3);
-
_parent.rewind();
- assertEquals("Unexpected position", (long) 0, (long) _parent.position());
- assertEquals("Unexpected limit", (long) expectedLimit, (long) _parent.limit());
- try
- {
- _parent.reset();
- fail("Expected exception not thrown");
- }
- catch (InvalidMarkException e)
- {
- // pass
- }
+ assertEquals(0, (long) _parent.position(), "Unexpected position");
+ assertEquals(expectedLimit, (long) _parent.limit(), "Unexpected limit");
+
+ assertThrows(InvalidMarkException.class, () -> _parent.reset(), "Expected exception not thrown");
}
@Test
- public void testBulkPutGet() throws Exception
+ public void testBulkPutGet()
{
_slicedBuffer = createSlice();
final byte[] source = getTestBytes(_slicedBuffer.remaining());
QpidByteBuffer rv = _slicedBuffer.put(source, 0, source.length);
- assertEquals("Unexpected builder return value", _slicedBuffer, rv);
+ assertEquals(_slicedBuffer, rv, "Unexpected builder return value");
_slicedBuffer.flip();
byte[] target = new byte[_slicedBuffer.remaining()];
rv = _slicedBuffer.get(target, 0, target.length);
- assertEquals("Unexpected builder return value", _slicedBuffer, rv);
-
- Assert.assertArrayEquals("Unexpected bulk put/get result", source, target);
+ assertEquals(_slicedBuffer, rv, "Unexpected builder return value");
+ assertArrayEquals(source, target, "Unexpected bulk put/get result");
_slicedBuffer.clear();
_slicedBuffer.position(1);
- try
- {
- _slicedBuffer.put(source, 0, source.length);
- fail("Exception not thrown");
- }
- catch (BufferOverflowException e)
- {
- // pass
- }
+ assertThrows(BufferOverflowException.class, () -> _slicedBuffer.put(source, 0, source.length),
+ "Expected exception not thrown");
- assertEquals("Position should be unchanged after failed put", (long) 1, (long) _slicedBuffer.position());
+ assertEquals(1, (long) _slicedBuffer.position(), "Position should be unchanged after failed put");
- try
- {
- _slicedBuffer.get(target, 0, target.length);
- fail("Exception not thrown");
- }
- catch (BufferUnderflowException e)
- {
- // pass
- }
+ assertThrows(BufferUnderflowException.class,() -> _slicedBuffer.get(target, 0, target.length),
+ "Expected exception not thrown");
- assertEquals("Position should be unchanged after failed get", (long) 1, (long) _slicedBuffer.position());
+ assertEquals(1, (long) _slicedBuffer.position(), "Position should be unchanged after failed get");
}
@Test
- public void testPutQpidByteBufferMultipleIntoMultiple() throws Exception
+ public void testPutQpidByteBufferMultipleIntoMultiple()
{
_slicedBuffer = createSlice();
@@ -280,19 +236,18 @@ public class QpidByteBufferTest extends UnitTestBase
_slicedBuffer.put(source);
_slicedBuffer.flip();
- try( QpidByteBuffer other = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+ try (final QpidByteBuffer other = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
{
other.put(_slicedBuffer);
-
other.flip();
- byte[] target = new byte[other.remaining()];
+ final byte[] target = new byte[other.remaining()];
other.get(target);
- Assert.assertArrayEquals("Unexpected put QpidByteBuffer result", source, target);
+ assertArrayEquals(source, target, "Unexpected put QpidByteBuffer result");
}
}
@Test
- public void testPutQpidByteBufferMultipleIntoSingle() throws Exception
+ public void testPutQpidByteBufferMultipleIntoSingle()
{
_slicedBuffer = createSlice();
@@ -300,48 +255,44 @@ public class QpidByteBufferTest extends UnitTestBase
_slicedBuffer.put(source);
_slicedBuffer.flip();
- try( QpidByteBuffer other = QpidByteBuffer.wrap(new byte[source.length]))
+ try (final QpidByteBuffer other = QpidByteBuffer.wrap(new byte[source.length]))
{
other.put(_slicedBuffer);
-
other.flip();
- byte[] target = new byte[other.remaining()];
+ final byte[] target = new byte[other.remaining()];
other.get(target);
- Assert.assertArrayEquals("Unexpected put QpidByteBuffer result", source, target);
+ assertArrayEquals(source, target, "Unexpected put QpidByteBuffer result");
}
}
@Test
- public void testPutQpidByteBufferSingleIntoMultiple() throws Exception
+ public void testPutQpidByteBufferSingleIntoMultiple()
{
_slicedBuffer = createSlice();
final byte[] source = getTestBytes(_slicedBuffer.remaining());
-
- try( QpidByteBuffer other = QpidByteBuffer.wrap(source))
+ try (final QpidByteBuffer other = QpidByteBuffer.wrap(source))
{
_slicedBuffer.put(other);
-
_slicedBuffer.flip();
- byte[] target = new byte[_slicedBuffer.remaining()];
+ final byte[] target = new byte[_slicedBuffer.remaining()];
_slicedBuffer.get(target);
- Assert.assertArrayEquals("Unexpected put QpidByteBuffer result", source, target);
+ assertArrayEquals(source, target, "Unexpected put QpidByteBuffer result");
}
}
@Test
- public void testPutByteBuffer() throws Exception
+ public void testPutByteBuffer()
{
final byte[] source = getTestBytes(_parent.remaining() - 1);
-
- ByteBuffer src = ByteBuffer.wrap(source);
+ final ByteBuffer src = ByteBuffer.wrap(source);
_parent.put(src);
_parent.flip();
- byte[] target = new byte[_parent.remaining()];
+ final byte[] target = new byte[_parent.remaining()];
_parent.get(target);
- Assert.assertArrayEquals("Unexpected but ByteBuffer result", source, target);
+ assertArrayEquals(source, target, "Unexpected but ByteBuffer result");
}
@Test
@@ -349,22 +300,20 @@ public class QpidByteBufferTest extends UnitTestBase
{
_slicedBuffer = createSlice();
_slicedBuffer.position(1);
- int originalLimit = _slicedBuffer.limit();
+ final int originalLimit = _slicedBuffer.limit();
_slicedBuffer.limit(originalLimit - 1);
- try (QpidByteBuffer duplicate = _slicedBuffer.duplicate())
+ try (final QpidByteBuffer duplicate = _slicedBuffer.duplicate())
{
- assertEquals("Unexpected position", (long) _slicedBuffer.position(), (long) duplicate.position());
- assertEquals("Unexpected limit", (long) _slicedBuffer.limit(), (long) duplicate.limit());
- assertEquals("Unexpected capacity", (long) _slicedBuffer.capacity(), (long) duplicate.capacity());
+ assertEquals(_slicedBuffer.position(), (long) duplicate.position(), "Unexpected position");
+ assertEquals(_slicedBuffer.limit(), (long) duplicate.limit(), "Unexpected limit");
+ assertEquals(_slicedBuffer.capacity(), (long) duplicate.capacity(), "Unexpected capacity");
duplicate.position(2);
duplicate.limit(originalLimit - 2);
- assertEquals("Unexpected position in the original", (long) 1, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit in the original",
- (long) (originalLimit - 1),
- (long) _slicedBuffer.limit());
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position in the original");
+ assertEquals(originalLimit - 1, (long) _slicedBuffer.limit(), "Unexpected limit in the original");
}
}
@@ -372,84 +321,76 @@ public class QpidByteBufferTest extends UnitTestBase
public void testCopyToByteBuffer()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.flip();
- int originalRemaining = _slicedBuffer.remaining();
- ByteBuffer destination = ByteBuffer.allocate(source.length);
+ final int originalRemaining = _slicedBuffer.remaining();
+ final ByteBuffer destination = ByteBuffer.allocate(source.length);
_slicedBuffer.copyTo(destination);
- assertEquals("Unexpected remaining in original QBB",
- (long) originalRemaining,
- (long) _slicedBuffer.remaining());
- assertEquals("Unexpected remaining in destination", (long) 0, (long) destination.remaining());
+ assertEquals(originalRemaining, (long) _slicedBuffer.remaining(), "Unexpected remaining in original QBB");
+ assertEquals(0, (long) destination.remaining(), "Unexpected remaining in destination");
- Assert.assertArrayEquals("Unexpected copyTo result", source, destination.array());
+ assertArrayEquals(source, destination.array(), "Unexpected copyTo result");
}
@Test
public void testCopyToArray()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.flip();
- int originalRemaining = _slicedBuffer.remaining();
- byte[] destination = new byte[source.length];
+ final int originalRemaining = _slicedBuffer.remaining();
+ final byte[] destination = new byte[source.length];
_slicedBuffer.copyTo(destination);
- assertEquals("Unexpected remaining in original QBB",
- (long) originalRemaining,
- (long) _slicedBuffer.remaining());
+ assertEquals(originalRemaining, (long) _slicedBuffer.remaining(), "Unexpected remaining in original QBB");
- Assert.assertArrayEquals("Unexpected copyTo result", source, destination);
+ assertArrayEquals(source, destination, "Unexpected copyTo result");
}
@Test
public void testPutCopyOfSingleIntoMultiple()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
- QpidByteBuffer sourceQpidByteBuffer = QpidByteBuffer.wrap(source);
+ final QpidByteBuffer sourceQpidByteBuffer = QpidByteBuffer.wrap(source);
_slicedBuffer.putCopyOf(sourceQpidByteBuffer);
- assertEquals("Copied buffer should not be changed",
- (long) source.length,
- (long) sourceQpidByteBuffer.remaining());
- assertEquals("Buffer should be full", (long) 0, (long) _slicedBuffer.remaining());
+ assertEquals(source.length, (long) sourceQpidByteBuffer.remaining(), "Copied buffer should not be changed");
+ assertEquals(0, (long) _slicedBuffer.remaining(), "Buffer should be full");
_slicedBuffer.flip();
- byte[] destination = new byte[source.length];
+ final byte[] destination = new byte[source.length];
_slicedBuffer.get(destination);
- Assert.assertArrayEquals("Unexpected putCopyOf result", source, destination);
+ assertArrayEquals(source, destination, "Unexpected putCopyOf result");
}
@Test
public void testPutCopyOfMultipleIntoSingle()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.flip();
- try (QpidByteBuffer target = QpidByteBuffer.wrap(new byte[source.length + 1]))
+ try (final QpidByteBuffer target = QpidByteBuffer.wrap(new byte[source.length + 1]))
{
target.putCopyOf(_slicedBuffer);
- assertEquals("Copied buffer should not be changed",
- (long) source.length,
- (long) _slicedBuffer.remaining());
- assertEquals("Unexpected remaining", (long) 1, (long) target.remaining());
+ assertEquals(source.length, (long) _slicedBuffer.remaining(),"Copied buffer should not be changed");
+ assertEquals(1, (long) target.remaining(), "Unexpected remaining");
target.flip();
- byte[] destination = new byte[source.length];
+ final byte[] destination = new byte[source.length];
target.get(destination);
- Assert.assertArrayEquals("Unexpected putCopyOf result", source, destination);
+ assertArrayEquals(source, destination, "Unexpected putCopyOf result");
}
}
@@ -457,24 +398,22 @@ public class QpidByteBufferTest extends UnitTestBase
public void testPutCopyOfMultipleIntoMultiple()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.flip();
- try (QpidByteBuffer target = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+ try (final QpidByteBuffer target = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
{
target.putCopyOf(_slicedBuffer);
- assertEquals("Copied buffer should not be changed",
- (long) source.length,
- (long) _slicedBuffer.remaining());
- assertEquals("Unexpected remaining", (long) 2, (long) target.remaining());
+ assertEquals(source.length, (long) _slicedBuffer.remaining(), "Copied buffer should not be changed");
+ assertEquals(2, (long) target.remaining(), "Unexpected remaining");
target.flip();
- byte[] destination = new byte[source.length];
+ final byte[] destination = new byte[source.length];
target.get(destination);
- Assert.assertArrayEquals("Unexpected putCopyOf result", source, destination);
+ assertArrayEquals(source, destination, "Unexpected putCopyOf result");
}
}
@@ -482,58 +421,55 @@ public class QpidByteBufferTest extends UnitTestBase
public void testCompact()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.position(1);
_slicedBuffer.limit(_slicedBuffer.limit() - 1);
- int remaining = _slicedBuffer.remaining();
+ final int remaining = _slicedBuffer.remaining();
_slicedBuffer.compact();
- assertEquals("Unexpected position", (long) remaining, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit", (long) _slicedBuffer.capacity(), (long) _slicedBuffer.limit());
+ assertEquals(remaining, (long) _slicedBuffer.position(), "Unexpected position");
+ assertEquals(_slicedBuffer.capacity(), (long) _slicedBuffer.limit(), "Unexpected limit");
_slicedBuffer.flip();
-
- byte[] destination = new byte[_slicedBuffer.remaining()];
+ final byte[] destination = new byte[_slicedBuffer.remaining()];
_slicedBuffer.get(destination);
- byte[] expected = new byte[source.length - 2];
+ final byte[] expected = new byte[source.length - 2];
System.arraycopy(source, 1, expected, 0, expected.length);
- Assert.assertArrayEquals("Unexpected compact result", expected, destination);
+ assertArrayEquals(expected, destination, "Unexpected compact result");
}
@Test
public void testSliceOfSlice()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.position(1);
_slicedBuffer.limit(_slicedBuffer.limit() - 1);
- int remaining = _slicedBuffer.remaining();
+ final int remaining = _slicedBuffer.remaining();
- try (QpidByteBuffer newSlice = _slicedBuffer.slice())
+ try (final QpidByteBuffer newSlice = _slicedBuffer.slice())
{
- assertEquals("Unexpected position in original", (long) 1, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit in original",
- (long) (source.length - 1),
- (long) _slicedBuffer.limit());
- assertEquals("Unexpected position", (long) 0, (long) newSlice.position());
- assertEquals("Unexpected limit", (long) remaining, (long) newSlice.limit());
- assertEquals("Unexpected capacity", (long) remaining, (long) newSlice.capacity());
-
- byte[] destination = new byte[newSlice.remaining()];
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position in original");
+ assertEquals(source.length - 1, (long) _slicedBuffer.limit(), "Unexpected limit in original");
+ assertEquals(0, (long) newSlice.position(), "Unexpected position");
+ assertEquals(remaining, (long) newSlice.limit(), "Unexpected limit");
+ assertEquals(remaining, (long) newSlice.capacity(), "Unexpected capacity");
+
+ final byte[] destination = new byte[newSlice.remaining()];
newSlice.get(destination);
- byte[] expected = new byte[source.length - 2];
+ final byte[] expected = new byte[source.length - 2];
System.arraycopy(source, 1, expected, 0, expected.length);
- Assert.assertArrayEquals("Unexpected slice result", expected, destination);
+ assertArrayEquals(expected, destination, "Unexpected slice result");
}
}
@@ -541,48 +477,44 @@ public class QpidByteBufferTest extends UnitTestBase
public void testViewOfSlice()
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.position(1);
_slicedBuffer.limit(_slicedBuffer.limit() - 1);
- try (QpidByteBuffer view = _slicedBuffer.view(0, _slicedBuffer.remaining()))
+ try (final QpidByteBuffer view = _slicedBuffer.view(0, _slicedBuffer.remaining()))
{
- assertEquals("Unexpected position in original", (long) 1, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit in original",
- (long) (source.length - 1),
- (long) _slicedBuffer.limit());
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position in original");
+ assertEquals(source.length - 1, (long) _slicedBuffer.limit(), "Unexpected limit in original");
- assertEquals("Unexpected position", (long) 0, (long) view.position());
- assertEquals("Unexpected limit", (long) _slicedBuffer.remaining(), (long) view.limit());
- assertEquals("Unexpected capacity", (long) _slicedBuffer.remaining(), (long) view.capacity());
+ assertEquals(0, (long) view.position(), "Unexpected position");
+ assertEquals(_slicedBuffer.remaining(), (long) view.limit(), "Unexpected limit");
+ assertEquals(_slicedBuffer.remaining(), (long) view.capacity(), "Unexpected capacity");
- byte[] destination = new byte[view.remaining()];
+ final byte[] destination = new byte[view.remaining()];
view.get(destination);
- byte[] expected = new byte[source.length - 2];
+ final byte[] expected = new byte[source.length - 2];
System.arraycopy(source, 1, expected, 0, expected.length);
- Assert.assertArrayEquals("Unexpected view result", expected, destination);
+ assertArrayEquals(expected, destination, "Unexpected view result");
}
- try (QpidByteBuffer view = _slicedBuffer.view(1, _slicedBuffer.remaining() - 2))
+ try (final QpidByteBuffer view = _slicedBuffer.view(1, _slicedBuffer.remaining() - 2))
{
- assertEquals("Unexpected position in original", (long) 1, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit in original",
- (long) (source.length - 1),
- (long) _slicedBuffer.limit());
+ assertEquals(1, (long) _slicedBuffer.position(), "Unexpected position in original");
+ assertEquals(source.length - 1, (long) _slicedBuffer.limit(), "Unexpected limit in original");
- assertEquals("Unexpected position", (long) 0, (long) view.position());
- assertEquals("Unexpected limit", (long) (_slicedBuffer.remaining() - 2), (long) view.limit());
- assertEquals("Unexpected capacity", (long) (_slicedBuffer.remaining() - 2), (long) view.capacity());
+ assertEquals(0, (long) view.position(), "Unexpected position");
+ assertEquals(_slicedBuffer.remaining() - 2, (long) view.limit(), "Unexpected limit");
+ assertEquals(_slicedBuffer.remaining() - 2, (long) view.capacity(), "Unexpected capacity");
- byte[] destination = new byte[view.remaining()];
+ final byte[] destination = new byte[view.remaining()];
view.get(destination);
- byte[] expected = new byte[source.length - 4];
+ final byte[] expected = new byte[source.length - 4];
System.arraycopy(source, 2, expected, 0, expected.length);
- Assert.assertArrayEquals("Unexpected view result", expected, destination);
+ assertArrayEquals(expected, destination, "Unexpected view result");
}
}
@@ -590,21 +522,21 @@ public class QpidByteBufferTest extends UnitTestBase
public void testAsInputStream() throws Exception
{
_slicedBuffer = createSlice();
- byte[] source = getTestBytes(_slicedBuffer.remaining());
+ final byte[] source = getTestBytes(_slicedBuffer.remaining());
_slicedBuffer.put(source);
_slicedBuffer.position(1);
_slicedBuffer.limit(_slicedBuffer.limit() - 1);
- ByteArrayOutputStream destination = new ByteArrayOutputStream();
- try(InputStream is = _slicedBuffer.asInputStream())
+ final ByteArrayOutputStream destination = new ByteArrayOutputStream();
+ try (final InputStream is = _slicedBuffer.asInputStream())
{
ByteStreams.copy(is, destination);
}
- byte[] expected = new byte[source.length - 2];
+ final byte[] expected = new byte[source.length - 2];
System.arraycopy(source, 1, expected, 0, expected.length);
- Assert.assertArrayEquals("Unexpected view result", expected, destination.toByteArray());
+ assertArrayEquals(expected, destination.toByteArray(), "Unexpected view result");
}
private byte[] getTestBytes(final int length)
@@ -621,13 +553,13 @@ public class QpidByteBufferTest extends UnitTestBase
{
_parent.position(1);
_parent.limit(_parent.capacity() - 1);
-
return _parent.slice();
}
- private void testPutGet(final Class<?> primitiveTargetClass, final boolean unsigned, final Object value) throws Exception
+ private void testPutGet(final Class<?> primitiveTargetClass, final boolean unsigned, final Object value)
+ throws Exception
{
- int size = sizeof(primitiveTargetClass);
+ final int size = sizeof(primitiveTargetClass);
_parent.position(1);
_parent.limit(size + 1);
@@ -635,55 +567,39 @@ public class QpidByteBufferTest extends UnitTestBase
_slicedBuffer = _parent.slice();
_parent.limit(_parent.capacity());
- assertEquals("Unexpected position ", (long) 0, (long) _slicedBuffer.position());
- assertEquals("Unexpected limit ", (long) size, (long) _slicedBuffer.limit());
- assertEquals("Unexpected capacity ", (long) size, (long) _slicedBuffer.capacity());
-
- String methodSuffix = getMethodSuffix(primitiveTargetClass, unsigned);
- Method put = _slicedBuffer.getClass().getMethod("put" + methodSuffix, Primitives.primitiveTypeOf(value.getClass()));
- Method get = _slicedBuffer.getClass().getMethod("get" + methodSuffix);
+ assertEquals(0, (long) _slicedBuffer.position(), "Unexpected position ");
+ assertEquals(size, (long) _slicedBuffer.limit(), "Unexpected limit ");
+ assertEquals(size, (long) _slicedBuffer.capacity(), "Unexpected capacity ");
+ final String methodSuffix = getMethodSuffix(primitiveTargetClass, unsigned);
+ final Method put = _slicedBuffer.getClass().getMethod("put" + methodSuffix, Primitives.primitiveTypeOf(value.getClass()));
+ final Method get = _slicedBuffer.getClass().getMethod("get" + methodSuffix);
_slicedBuffer.mark();
- QpidByteBuffer rv = (QpidByteBuffer) put.invoke(_slicedBuffer, value);
- assertEquals("Unexpected builder return value for type " + methodSuffix, _slicedBuffer, rv);
+ final QpidByteBuffer rv = (QpidByteBuffer) put.invoke(_slicedBuffer, value);
+ assertEquals(_slicedBuffer, rv, "Unexpected builder return value for type " + methodSuffix);
- assertEquals("Unexpected position for type " + methodSuffix,
- (long) size,
- (long) _slicedBuffer.position());
+ assertEquals(size, (long) _slicedBuffer.position(), "Unexpected position for type " + methodSuffix);
- try
- {
- invokeMethod(put, value);
- fail("BufferOverflowException should be thrown for put with insufficient room for " + methodSuffix);
- }
- catch (BufferOverflowException e)
- {
- // pass
- }
+ assertThrows(BufferOverflowException.class, () -> invokeMethod(put, value),
+ "BufferOverflowException should be thrown for put with insufficient room for " + methodSuffix);
_slicedBuffer.reset();
- assertEquals("Unexpected position after reset", (long) 0, (long) _slicedBuffer.position());
+ assertEquals(0, (long) _slicedBuffer.position(), "Unexpected position after reset");
Object retrievedValue = get.invoke(_slicedBuffer);
- assertEquals("Unexpected value retrieved from get method for " + methodSuffix, value, retrievedValue);
- try
- {
- invokeMethod(get);
- fail("BufferUnderflowException not thrown for get with insufficient room for " + methodSuffix);
- }
- catch (BufferUnderflowException ite)
- {
- // pass
- }
+ assertEquals(value, retrievedValue, "Unexpected value retrieved from get method for " + methodSuffix);
+ assertThrows(BufferUnderflowException.class, () -> invokeMethod(get),
+ "BufferUnderflowException not thrown for get with insufficient room for " + methodSuffix);
+
_slicedBuffer.dispose();
_slicedBuffer = null;
}
private void testPutGetByIndex(final Class<?> primitiveTargetClass, Object value) throws Exception
{
- int size = sizeof(primitiveTargetClass);
+ final int size = sizeof(primitiveTargetClass);
_parent.position(1);
_parent.limit(size + 1);
@@ -691,63 +607,30 @@ public class QpidByteBufferTest extends UnitTestBase
_slicedBuffer = _parent.slice();
_parent.limit(_parent.capacity());
- String methodSuffix = getMethodSuffix(primitiveTargetClass, false);
- Method put = _slicedBuffer.getClass().getMethod("put" + methodSuffix, int.class, primitiveTargetClass);
- Method get = _slicedBuffer.getClass().getMethod("get" + methodSuffix, int.class);
-
- QpidByteBuffer rv = (QpidByteBuffer) put.invoke(_slicedBuffer, 0, value);
- assertEquals("Unexpected builder return value for type " + methodSuffix, _slicedBuffer, rv);
-
- Object retrievedValue = get.invoke(_slicedBuffer, 0);
- assertEquals("Unexpected value retrieved from index get method for " + methodSuffix,
- value,
- retrievedValue);
-
- try
- {
- invokeMethod(put, 1, value);
- fail("IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " put");
- }
- catch (IndexOutOfBoundsException ite)
- {
- // pass
- }
-
- try
- {
- invokeMethod(put, -1, value);
- fail("IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " put with negative index");
- }
- catch (IndexOutOfBoundsException ite)
- {
- // pass
- }
+ final String methodSuffix = getMethodSuffix(primitiveTargetClass, false);
+ final Method put = _slicedBuffer.getClass().getMethod("put" + methodSuffix, int.class, primitiveTargetClass);
+ final Method get = _slicedBuffer.getClass().getMethod("get" + methodSuffix, int.class);
+
+ final QpidByteBuffer rv = (QpidByteBuffer) put.invoke(_slicedBuffer, 0, value);
+ assertEquals(_slicedBuffer, rv, "Unexpected builder return value for type " + methodSuffix);
+
+ final Object retrievedValue = get.invoke(_slicedBuffer, 0);
+ assertEquals(value, retrievedValue,
+ "Unexpected value retrieved from index get method for " + methodSuffix);
+ assertThrows(IndexOutOfBoundsException.class, () -> invokeMethod(put, 1, value),
+ "IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " put");
+ assertThrows(IndexOutOfBoundsException.class, () -> invokeMethod(put, -1, value),
+ "IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " put with negative index");
+ assertThrows(IndexOutOfBoundsException.class, () -> invokeMethod(get, 1),
+ "IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " get");
+ assertThrows(IndexOutOfBoundsException.class, () -> invokeMethod(get, -1),
+ "IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " get with negative index");
- try
- {
- invokeMethod(get, 1);
- fail("IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " get");
- }
- catch (IndexOutOfBoundsException ite)
- {
- // pass
- }
-
- try
- {
- invokeMethod(get, -1);
- fail("IndexOutOfBoundsException not thrown for indexed " + methodSuffix + " get with negative index");
- }
- catch (IndexOutOfBoundsException ite)
- {
- // pass
- }
_slicedBuffer.dispose();
_slicedBuffer = null;
}
- private void invokeMethod(final Method method, final Object... value)
- throws Exception
+ private void invokeMethod(final Method method, final Object... value) throws Exception
{
try
{
@@ -755,7 +638,7 @@ public class QpidByteBufferTest extends UnitTestBase
}
catch (InvocationTargetException e)
{
- Throwable cause = e.getCause();
+ final Throwable cause = e.getCause();
if (cause instanceof Exception)
{
throw (Exception)cause;
@@ -764,20 +647,18 @@ public class QpidByteBufferTest extends UnitTestBase
}
}
-
private String getMethodSuffix(final Class<?> target, final boolean unsigned)
{
- StringBuilder name = new StringBuilder();
+ final StringBuilder name = new StringBuilder();
if (unsigned)
{
name.append("Unsigned");
}
if ((!target.isAssignableFrom(byte.class) || unsigned))
{
- String simpleName = target.getSimpleName();
+ final String simpleName = target.getSimpleName();
name.append(simpleName.substring(0, 1).toUpperCase()).append(simpleName.substring(1));
}
-
return name.toString();
}
@@ -818,58 +699,58 @@ public class QpidByteBufferTest extends UnitTestBase
}
@Test
- public void testPooledBufferIsZeroedLoan() throws Exception
+ public void testPooledBufferIsZeroedLoan()
{
- try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
{
buffer.put((byte) 0xFF);
}
- try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
{
buffer.limit(1);
- assertEquals("Pooled QpidByteBuffer is not zeroed.", (long) (byte) 0x0, (long) buffer.get());
+ assertEquals((byte) 0x0, (long) buffer.get(), "Pooled QpidByteBuffer is not zeroed.");
}
}
@Test
- public void testAllocateDirectOfSameSize() throws Exception
+ public void testAllocateDirectOfSameSize()
{
- int bufferSize = BUFFER_SIZE;
- try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+ final int bufferSize = BUFFER_SIZE;
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
{
- assertEquals("Unexpected buffer size", (long) bufferSize, (long) buffer.capacity());
- assertEquals("Unexpected position on newly created buffer", (long) 0, (long) buffer.position());
- assertEquals("Unexpected limit on newly created buffer", (long) bufferSize, (long) buffer.limit());
+ assertEquals(bufferSize, (long) buffer.capacity(), "Unexpected buffer size");
+ assertEquals(0, (long) buffer.position(), "Unexpected position on newly created buffer");
+ assertEquals(bufferSize, (long) buffer.limit(), "Unexpected limit on newly created buffer");
}
}
@Test
- public void testAllocateDirectOfSmallerSize() throws Exception
+ public void testAllocateDirectOfSmallerSize()
{
- int bufferSize = BUFFER_SIZE - 1;
- try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+ final int bufferSize = BUFFER_SIZE - 1;
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
{
- assertEquals("Unexpected buffer size", (long) bufferSize, (long) buffer.capacity());
- assertEquals("Unexpected position on newly created buffer", (long) 0, (long) buffer.position());
- assertEquals("Unexpected limit on newly created buffer", (long) bufferSize, (long) buffer.limit());
+ assertEquals(bufferSize, (long) buffer.capacity(), "Unexpected buffer size");
+ assertEquals(0, (long) buffer.position(), "Unexpected position on newly created buffer");
+ assertEquals(bufferSize, (long) buffer.limit(), "Unexpected limit on newly created buffer");
}
}
@Test
- public void testAllocateDirectOfLargerSize() throws Exception
+ public void testAllocateDirectOfLargerSize()
{
- int bufferSize = BUFFER_SIZE + 1;
- try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+ final int bufferSize = BUFFER_SIZE + 1;
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
{
- assertEquals("Unexpected buffer size", (long) bufferSize, (long) buffer.capacity());
- assertEquals("Unexpected position on newly created buffer", (long) 0, (long) buffer.position());
- assertEquals("Unexpected limit on newly created buffer", (long) bufferSize, (long) buffer.limit());
+ assertEquals(bufferSize, (long) buffer.capacity(), "Unexpected buffer size");
+ assertEquals(0, (long) buffer.position(), "Unexpected position on newly created buffer");
+ assertEquals(bufferSize, (long) buffer.limit(), "Unexpected limit on newly created buffer");
}
}
@Test
- public void testAllocateDirectWithNegativeSize() throws Exception
+ public void testAllocateDirectWithNegativeSize()
{
try
{
@@ -883,7 +764,7 @@ public class QpidByteBufferTest extends UnitTestBase
}
@Test
- public void testSettingUpPoolTwice() throws Exception
+ public void testSettingUpPoolTwice()
{
try
{
@@ -899,13 +780,13 @@ public class QpidByteBufferTest extends UnitTestBase
@Test
public void testDeflateInflateDirect() throws Exception
{
- byte[] input = "aaabbbcccddddeeeffff".getBytes();
- try (QpidByteBuffer inputBuf = QpidByteBuffer.allocateDirect(input.length))
+ final byte[] input = "aaabbbcccddddeeeffff".getBytes();
+ try (final QpidByteBuffer inputBuf = QpidByteBuffer.allocateDirect(input.length))
{
inputBuf.put(input);
inputBuf.flip();
- assertEquals((long) input.length, (long) inputBuf.remaining());
+ assertEquals(input.length, (long) inputBuf.remaining());
doDeflateInflate(input, inputBuf, true);
}
@@ -914,9 +795,8 @@ public class QpidByteBufferTest extends UnitTestBase
@Test
public void testDeflateInflateHeap() throws Exception
{
- byte[] input = "aaabbbcccddddeeeffff".getBytes();
-
- try (QpidByteBuffer buffer = QpidByteBuffer.wrap(input))
+ final byte[] input = "aaabbbcccddddeeeffff".getBytes();
+ try (final QpidByteBuffer buffer = QpidByteBuffer.wrap(input))
{
doDeflateInflate(input, buffer, false);
}
@@ -925,9 +805,8 @@ public class QpidByteBufferTest extends UnitTestBase
@Test
public void testInflatingUncompressedBytes_ThrowsZipException() throws Exception
{
- byte[] input = "not_a_compressed_stream".getBytes();
-
- try (QpidByteBuffer original = QpidByteBuffer.wrap(input))
+ final byte[] input = "not_a_compressed_stream".getBytes();
+ try (final QpidByteBuffer original = QpidByteBuffer.wrap(input))
{
QpidByteBuffer.inflate(original);
fail("Exception not thrown");
@@ -939,49 +818,49 @@ public class QpidByteBufferTest extends UnitTestBase
}
@Test
- public void testSlice() throws Exception
+ public void testSlice()
{
- try (QpidByteBuffer directBuffer = QpidByteBuffer.allocate(true, 6))
+ try (final QpidByteBuffer directBuffer = QpidByteBuffer.allocate(true, 6))
{
directBuffer.position(2);
directBuffer.limit(5);
- try (QpidByteBuffer directSlice = directBuffer.slice())
+ try (final QpidByteBuffer directSlice = directBuffer.slice())
{
- assertTrue("Direct slice should be direct too", directSlice.isDirect());
- assertEquals("Unexpected capacity", (long) 3, (long) directSlice.capacity());
- assertEquals("Unexpected limit", (long) 3, (long) directSlice.limit());
- assertEquals("Unexpected position", (long) 0, (long) directSlice.position());
+ assertTrue(directSlice.isDirect(), "Direct slice should be direct too");
+ assertEquals(3, (long) directSlice.capacity(), "Unexpected capacity");
+ assertEquals(3, (long) directSlice.limit(), "Unexpected limit");
+ assertEquals(0, (long) directSlice.position(), "Unexpected position");
}
}
}
@Test
- public void testView() throws Exception
+ public void testView()
{
- byte[] content = "ABCDEF".getBytes();
- try (QpidByteBuffer buffer = QpidByteBuffer.allocate(true, content.length))
+ final byte[] content = "ABCDEF".getBytes();
+ try (final QpidByteBuffer buffer = QpidByteBuffer.allocate(true, content.length))
{
buffer.put(content);
buffer.position(2);
buffer.limit(5);
- try (QpidByteBuffer view = buffer.view(0, buffer.remaining()))
+ try (final QpidByteBuffer view = buffer.view(0, buffer.remaining()))
{
- assertTrue("Unexpected view direct", view.isDirect());
- assertEquals("Unexpected capacity", (long) 3, (long) view.capacity());
- assertEquals("Unexpected limit", (long) 3, (long) view.limit());
- assertEquals("Unexpected position", (long) 0, (long) view.position());
+ assertTrue(view.isDirect(), "Unexpected view direct");
+ assertEquals(3, (long) view.capacity(), "Unexpected capacity");
+ assertEquals(3, (long) view.limit(), "Unexpected limit");
+ assertEquals(0, (long) view.position(), "Unexpected position");
final byte[] destination = new byte[view.remaining()];
view.get(destination);
- Assert.assertArrayEquals("CDE".getBytes(), destination);
+ assertArrayEquals("CDE".getBytes(), destination);
}
- try (QpidByteBuffer viewWithOffset = buffer.view(1, 1))
+ try (final QpidByteBuffer viewWithOffset = buffer.view(1, 1))
{
final byte[] destination = new byte[viewWithOffset.remaining()];
viewWithOffset.get(destination);
- Assert.assertArrayEquals("D".getBytes(), destination);
+ assertArrayEquals("D".getBytes(), destination);
}
}
}
@@ -989,43 +868,41 @@ public class QpidByteBufferTest extends UnitTestBase
@Test
public void testSparsity()
{
- assertFalse("Unexpected sparsity after creation", _parent.isSparse());
- QpidByteBuffer child = _parent.view(0, 8);
- QpidByteBuffer grandChild = child.view(0, 2);
+ assertFalse(_parent.isSparse(), "Unexpected sparsity after creation");
+ final QpidByteBuffer child = _parent.view(0, 8);
+ final QpidByteBuffer grandChild = child.view(0, 2);
- assertFalse("Unexpected sparsity after child creation", _parent.isSparse());
+ assertFalse(_parent.isSparse(), "Unexpected sparsity after child creation");
_parent.dispose();
_parent = null;
- assertFalse("Unexpected sparsity after parent disposal", child.isSparse());
+ assertFalse(child.isSparse(), "Unexpected sparsity after parent disposal");
child.dispose();
- assertTrue("Buffer should be sparse", grandChild.isSparse());
+ assertTrue(grandChild.isSparse(), "Buffer should be sparse");
grandChild.dispose();
}
@Test
public void testAsQpidByteBuffers() throws IOException
{
- byte[] dataForTwoBufs = "01234567890".getBytes(StandardCharsets.US_ASCII);
- try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(dataForTwoBufs)))
+ final byte[] dataForTwoBufs = "01234567890".getBytes(StandardCharsets.US_ASCII);
+ try (final QpidByteBuffer qpidByteBuffer = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(dataForTwoBufs)))
{
- assertEquals("Unexpected remaining in buf", (long) 11, (long) qpidByteBuffer.remaining());
+ assertEquals(11, (long) qpidByteBuffer.remaining(), "Unexpected remaining in buf");
}
- try (QpidByteBuffer bufsForEmptyBytes = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(new byte[]{})))
+ try (final QpidByteBuffer bufsForEmptyBytes = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(new byte[]{})))
{
- assertEquals("Unexpected remaining in buf for empty buffer",
- (long) 0,
- (long) bufsForEmptyBytes.remaining());
+ assertEquals(0, (long) bufsForEmptyBytes.remaining(), "Unexpected remaining in buf for empty buffer");
}
}
@Test
- public void testConcatenate() throws Exception
+ public void testConcatenate()
{
- try (QpidByteBuffer buffer1 = QpidByteBuffer.allocateDirect(10);
- QpidByteBuffer buffer2 = QpidByteBuffer.allocateDirect(10))
+ try (final QpidByteBuffer buffer1 = QpidByteBuffer.allocateDirect(10);
+ final QpidByteBuffer buffer2 = QpidByteBuffer.allocateDirect(10))
{
final short buffer1Value = (short) (1 << 15);
buffer1.putShort(buffer1Value);
@@ -1035,41 +912,38 @@ public class QpidByteBufferTest extends UnitTestBase
buffer2.position(4);
buffer2.flip();
- try (QpidByteBuffer concatenate = QpidByteBuffer.concatenate(buffer1, buffer2))
+ try (final QpidByteBuffer concatenate = QpidByteBuffer.concatenate(buffer1, buffer2))
{
- assertEquals("Unexpected capacity", (long) 6, (long) concatenate.capacity());
- assertEquals("Unexpected position", (long) 0, (long) concatenate.position());
- assertEquals("Unexpected limit", (long) 6, (long) concatenate.limit());
- assertEquals("Unexpected value 1", (long) buffer1Value, (long) concatenate.getShort());
- assertEquals("Unexpected value 2", (long) buffer2Value, (long) concatenate.getChar(4));
+ assertEquals(6, (long) concatenate.capacity(), "Unexpected capacity");
+ assertEquals(0, (long) concatenate.position(), "Unexpected position");
+ assertEquals(6, (long) concatenate.limit(), "Unexpected limit");
+ assertEquals(buffer1Value, (long) concatenate.getShort(), "Unexpected value 1");
+ assertEquals(buffer2Value, (long) concatenate.getChar(4), "Unexpected value 2");
}
}
}
- private void doDeflateInflate(byte[] input,
- QpidByteBuffer inputBuf,
- boolean direct) throws IOException
+ private void doDeflateInflate(final byte[] input,
+ final QpidByteBuffer inputBuf,
+ final boolean direct) throws IOException
{
- try (QpidByteBuffer deflatedBuf = QpidByteBuffer.deflate(inputBuf))
+ try (final QpidByteBuffer deflatedBuf = QpidByteBuffer.deflate(inputBuf))
{
assertNotNull(deflatedBuf);
- try (QpidByteBuffer inflatedBuf = QpidByteBuffer.inflate(deflatedBuf))
+ try (final QpidByteBuffer inflatedBuf = QpidByteBuffer.inflate(deflatedBuf))
{
assertNotNull(inflatedBuf);
- int inflatedBytesCount = inflatedBuf.remaining();
+ final int inflatedBytesCount = inflatedBuf.remaining();
- byte[] inflatedBytes = new byte[inflatedBytesCount];
+ final byte[] inflatedBytes = new byte[inflatedBytesCount];
inflatedBuf.get(inflatedBytes);
- byte[] expectedBytes = Arrays.copyOfRange(input, 0, inflatedBytes.length);
- Assert.assertArrayEquals("Inflated buf has unexpected content", expectedBytes, inflatedBytes);
+ final byte[] expectedBytes = Arrays.copyOfRange(input, 0, inflatedBytes.length);
+ assertArrayEquals(expectedBytes, inflatedBytes, "Inflated buf has unexpected content");
- assertEquals("Unexpected number of inflated bytes",
- (long) input.length,
- (long) inflatedBytesCount);
+ assertEquals(input.length, (long) inflatedBytesCount, "Unexpected number of inflated bytes");
}
}
}
-
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java b/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java
index 7db67d9bf8..2cc1899db0 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java
@@ -20,19 +20,18 @@
*/
package org.apache.qpid.server.configuration.startup;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
-import java.util.UUID;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
@@ -53,23 +52,24 @@ import org.apache.qpid.test.utils.UnitTestBase;
public class VirtualHostCreationTest extends UnitTestBase
{
+ @SuppressWarnings("rawtypes")
private VirtualHostNode _virtualHostNode;
- @Before
+ @BeforeEach
+ @SuppressWarnings({"rawtypes"})
public void setUp() throws Exception
{
-
- EventLogger eventLogger = mock(EventLogger.class);
- TaskExecutor executor = CurrentThreadTaskExecutor.newStartedInstance();
- SystemConfig systemConfig = mock(SystemConfig.class);
- ConfiguredObjectFactory objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance());
+ final EventLogger eventLogger = mock(EventLogger.class);
+ final TaskExecutor executor = CurrentThreadTaskExecutor.newStartedInstance();
+ final SystemConfig systemConfig = mock(SystemConfig.class);
+ final ConfiguredObjectFactory objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance());
when(systemConfig.getObjectFactory()).thenReturn(objectFactory);
when(systemConfig.getModel()).thenReturn(objectFactory.getModel());
when(systemConfig.getEventLogger()).thenReturn(eventLogger);
when(systemConfig.getTaskExecutor()).thenReturn(executor);
when(systemConfig.getChildExecutor()).thenReturn(executor);
- Broker broker = mock(Broker.class);
+ final Broker broker = mock(Broker.class);
when(broker.getObjectFactory()).thenReturn(objectFactory);
when(broker.getModel()).thenReturn(objectFactory.getModel());
when(broker.getCategoryClass()).thenReturn(Broker.class);
@@ -90,48 +90,41 @@ public class VirtualHostCreationTest extends UnitTestBase
@Test
public void testCreateVirtualHostFromStoreConfigAttributes()
{
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(VirtualHost.NAME, getTestName());
- attributes.put(VirtualHost.TYPE, TestMemoryVirtualHost.VIRTUAL_HOST_TYPE);
- attributes.put(VirtualHost.ID, UUID.randomUUID());
-
- VirtualHost<?> host = new TestMemoryVirtualHost(attributes, _virtualHostNode);
+ final Map<String, Object> attributes = Map.of(VirtualHost.NAME, getTestName(),
+ VirtualHost.TYPE, TestMemoryVirtualHost.VIRTUAL_HOST_TYPE,
+ VirtualHost.ID, randomUUID());
+ final VirtualHost<?> host = new TestMemoryVirtualHost(attributes, _virtualHostNode);
host.open();
- assertNotNull("Null is returned", host);
- assertEquals("Unexpected name", getTestName(), host.getName());
+ assertNotNull(host, "Null is returned");
+ assertEquals(getTestName(), host.getName(), "Unexpected name");
host.close();
}
@Test
public void testCreateWithoutMandatoryAttributesResultsInException()
{
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(VirtualHost.NAME, getTestName());
- attributes.put(VirtualHost.TYPE, TestMemoryVirtualHost.VIRTUAL_HOST_TYPE);
- String[] mandatoryAttributes = {VirtualHost.NAME};
-
+ final Map<String, Object> attributes = Map.of(VirtualHost.NAME, getTestName(),
+ VirtualHost.TYPE, TestMemoryVirtualHost.VIRTUAL_HOST_TYPE);
+ final String[] mandatoryAttributes = { VirtualHost.NAME };
checkMandatoryAttributesAreValidated(mandatoryAttributes, attributes);
}
- public void checkMandatoryAttributesAreValidated(String[] mandatoryAttributes, Map<String, Object> attributes)
+ public void checkMandatoryAttributesAreValidated(final String[] mandatoryAttributes,
+ final Map<String, Object> attributes)
{
- for (String name : mandatoryAttributes)
+ for (final String name : mandatoryAttributes)
{
- Map<String, Object> copy = new HashMap<String, Object>(attributes);
+ final Map<String, Object> copy = new HashMap<>(attributes);
copy.remove(name);
- copy.put(ConfiguredObject.ID, UUID.randomUUID());
+ copy.put(ConfiguredObject.ID, randomUUID());
try
{
- VirtualHost<?> host = new TestMemoryVirtualHost(copy, _virtualHostNode);
+ final VirtualHost<?> host = new TestMemoryVirtualHost(copy, _virtualHostNode);
host.open();
fail("Cannot create a virtual host without a mandatory attribute " + name);
}
- catch(IllegalConfigurationException e)
- {
- // pass
- }
- catch(IllegalArgumentException e)
+ catch(IllegalConfigurationException | IllegalArgumentException e)
{
// pass
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java b/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java
index f47476b65a..94501b0492 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java
@@ -20,9 +20,10 @@
*/
package org.apache.qpid.server.configuration.store;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertIterableEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doAnswer;
@@ -35,18 +36,18 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
+import java.util.stream.Collectors;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
@@ -61,7 +62,6 @@ import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.server.model.State;
import org.apache.qpid.server.model.StateTransition;
import org.apache.qpid.server.model.SystemConfig;
-import org.apache.qpid.server.model.VirtualHost;
import org.apache.qpid.server.model.VirtualHostNode;
import org.apache.qpid.server.store.ConfiguredObjectRecord;
import org.apache.qpid.server.store.ConfiguredObjectRecordImpl;
@@ -77,65 +77,54 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
private ConfiguredObjectRecord _root;
private ConfiguredObjectRecord _portEntry;
private UUID _rootId, _portEntryId;
- private SystemConfig _systemConfig;
+ private SystemConfig<?> _systemConfig;
private TaskExecutor _taskExecutor;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- _rootId = UUID.randomUUID();
- _portEntryId = UUID.randomUUID();
+ _rootId = randomUUID();
+ _portEntryId = randomUUID();
_store = mock(DurableConfigurationStore.class);
_taskExecutor = new CurrentThreadTaskExecutor();
_taskExecutor.start();
- _systemConfig = new JsonSystemConfigImpl(_taskExecutor, mock(EventLogger.class),
- null, new HashMap<String, Object>());
-
-
- ConfiguredObjectRecord systemContextRecord = _systemConfig.asObjectRecord();
-
+ _systemConfig = new JsonSystemConfigImpl(_taskExecutor, mock(EventLogger.class),null, Map.of());
+ final ConfiguredObjectRecord systemContextRecord = _systemConfig.asObjectRecord();
- _root = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), Collections.singletonMap(Broker.NAME,
- (Object) "broker"), Collections.singletonMap(SystemConfig.class.getSimpleName(), systemContextRecord.getId()));
+ _root = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), Map.of(Broker.NAME, "broker"), Map.of(SystemConfig.class.getSimpleName(), systemContextRecord.getId()));
_portEntry = mock(ConfiguredObjectRecord.class);
when(_portEntry.getId()).thenReturn(_portEntryId);
- when(_portEntry.getParents()).thenReturn(Collections.singletonMap(Broker.class.getSimpleName(), _root.getId()));
+ when(_portEntry.getParents()).thenReturn(Map.of(Broker.class.getSimpleName(), _root.getId()));
when(_portEntry.getType()).thenReturn(Port.class.getSimpleName());
- final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class);
- doAnswer(
- new Answer()
- {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable
- {
- ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue();
- recoverer.handle(_root);
- recoverer.handle(_portEntry);
- return false;
- }
- }
- ).when(_store).openConfigurationStore(recovererArgumentCaptor.capture());
+ final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor =
+ ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class);
+ doAnswer(invocation ->
+ {
+ final ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue();
+ recoverer.handle(_root);
+ recoverer.handle(_portEntry);
+ return false;
+ }).when(_store).openConfigurationStore(recovererArgumentCaptor.capture());
_systemConfigAttributes = new HashMap<>();
- _handler = new ManagementModeStoreHandler(_store, _systemConfig);;
+ _handler = new ManagementModeStoreHandler(_store, _systemConfig);
_handler.init(_systemConfig);
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
private ManagementModeStoreHandler createManagementModeStoreHandler()
{
_systemConfig.close();
- Map<String, Object> attributes = new HashMap<>(_systemConfigAttributes);
+ final Map<String, Object> attributes = new HashMap<>(_systemConfigAttributes);
attributes.put(ConfiguredObject.DESIRED_STATE, State.QUIESCED);
attributes.remove(ConfiguredObject.TYPE);
- _systemConfig = new AbstractSystemConfig(_taskExecutor,
- mock(EventLogger.class),
- mock(Principal.class), attributes)
+ _systemConfig = new AbstractSystemConfig(_taskExecutor, mock(EventLogger.class),mock(Principal.class), attributes)
{
@Override
protected void onOpen()
@@ -165,7 +154,7 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
return new ManagementModeStoreHandler(_store, _systemConfig);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
_taskExecutor.stop();
@@ -175,73 +164,37 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
private Collection<ConfiguredObjectRecord> openAndGetRecords()
{
final Collection<ConfiguredObjectRecord> records = new ArrayList<>();
- _handler.openConfigurationStore(new ConfiguredObjectRecordHandler()
- {
-
- @Override
- public void handle(final ConfiguredObjectRecord record)
- {
- records.add(record);
- }
-
- });
+ _handler.openConfigurationStore(records::add);
return records;
}
private ConfiguredObjectRecord getRootEntry(Collection<ConfiguredObjectRecord> records)
{
- for(ConfiguredObjectRecord record : records)
- {
- if (record.getType().equals(Broker.class.getSimpleName()))
- {
- return record;
- }
- }
- return null;
+ final String brokerClassName = Broker.class.getSimpleName();
+ return records.stream().filter(record -> record.getType().equals(brokerClassName)).findFirst().orElse(null);
}
private ConfiguredObjectRecord getEntry(Collection<ConfiguredObjectRecord> records, UUID id)
{
- for(ConfiguredObjectRecord record : records)
- {
- if (record.getId().equals(id))
- {
- return record;
- }
- }
- return null;
+ return records.stream().filter(record -> record.getId().equals(id)).findFirst().orElse(null);
}
- private Collection<UUID> getChildrenIds(Collection<ConfiguredObjectRecord> records, ConfiguredObjectRecord parent)
+ private Collection<UUID> getChildrenIds(final Collection<ConfiguredObjectRecord> records,
+ final ConfiguredObjectRecord parent)
{
- Collection<UUID> childIds = new HashSet<>();
-
- for(ConfiguredObjectRecord record : records)
- {
-
- if (record.getParents() != null)
- {
- for (UUID parentId : record.getParents().values())
- {
- if (parentId.equals(parent.getId()))
- {
- childIds.add(record.getId());
- }
- }
-
- }
- }
-
- return childIds;
+ return records.stream().filter(record -> record.getParents() != null)
+ .filter(record -> record.getParents().values().stream().anyMatch(id -> id.equals(parent.getId())))
+ .map(ConfiguredObjectRecord::getId)
+ .collect(Collectors.toList());
}
@Test
public void testGetRootEntryWithEmptyOptions()
{
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
- ConfiguredObjectRecord root = getRootEntry(records);
- assertEquals("Unexpected root id", _rootId, root.getId());
- assertEquals("Unexpected children", Collections.singleton(_portEntryId), getChildrenIds(records, root));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord root = getRootEntry(records);
+ assertEquals(_rootId, root.getId(), "Unexpected root id");
+ assertIterableEquals(Set.of(_portEntryId), getChildrenIds(records, root), "Unexpected children");
}
@Test
@@ -250,13 +203,12 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord root = getRootEntry(records);
- assertEquals("Unexpected root id", _rootId, root.getId());
- Collection<UUID> childrenIds = getChildrenIds(records, root);
- assertEquals("Unexpected children size", (long) 2, (long) childrenIds.size());
- assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord root = getRootEntry(records);
+ assertEquals(_rootId, root.getId(), "Unexpected root id");
+ final Collection<UUID> childrenIds = getChildrenIds(records, root);
+ assertEquals(2, (long) childrenIds.size(), "Unexpected children size");
+ assertTrue(childrenIds.contains(_portEntryId), "Store port entry id is not found");
}
@Test
@@ -265,34 +217,31 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord root = getRootEntry(records);
- assertEquals("Unexpected root id", _rootId, root.getId());
- Collection<UUID> childrenIds = getChildrenIds(records, root);
- assertEquals("Unexpected children size", (long) 2, (long) childrenIds.size());
- assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord root = getRootEntry(records);
+ assertEquals(_rootId, root.getId(), "Unexpected root id");
+ final Collection<UUID> childrenIds = getChildrenIds(records, root);
+ assertEquals(2, (long) childrenIds.size(), "Unexpected children size");
+ assertTrue(childrenIds.contains(_portEntryId), "Store port entry id is not found");
}
@Test
public void testGetEntryByRootId()
{
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord root = getEntry(records, _rootId);
- assertEquals("Unexpected root id", _rootId, root.getId());
- assertEquals("Unexpected children", Collections.singleton(_portEntryId), getChildrenIds(records, root));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord root = getEntry(records, _rootId);
+ assertEquals(_rootId, root.getId(), "Unexpected root id");
+ assertIterableEquals(Set.of(_portEntryId), getChildrenIds(records, root), "Unexpected children");
}
@Test
public void testGetEntryByPortId()
{
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord portEntry = getEntry(records, _portEntryId);
- assertEquals("Unexpected entry id", _portEntryId, portEntry.getId());
- assertTrue("Unexpected children", getChildrenIds(records, portEntry).isEmpty());
- assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.DESIRED_STATE));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord portEntry = getEntry(records, _portEntryId);
+ assertEquals(_portEntryId, portEntry.getId(), "Unexpected entry id");
+ assertTrue(getChildrenIds(records, portEntry).isEmpty(), "Unexpected children");
+ assertEquals(State.QUIESCED, portEntry.getAttributes().get(Port.DESIRED_STATE), "Unexpected state");
}
@Test
@@ -302,27 +251,23 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- UUID optionsPort = getOptionsPortId(records);
- ConfiguredObjectRecord portEntry = getEntry(records, optionsPort);
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final UUID optionsPort = getOptionsPortId(records);
+ final ConfiguredObjectRecord portEntry = getEntry(records, optionsPort);
assertCLIPortEntry(records, portEntry, optionsPort, Protocol.HTTP);
}
@Test
public void testHttpPortEntryIsQuiesced()
{
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.HTTP));
+ final Map<String, Object> attributes = Map.of(Port.PROTOCOLS, Set.of(Protocol.HTTP));
when(_portEntry.getAttributes()).thenReturn(attributes);
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
-
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord portEntry = getEntry(records, _portEntryId);
- assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.DESIRED_STATE));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord portEntry = getEntry(records, _portEntryId);
+ assertEquals(State.QUIESCED, portEntry.getAttributes().get(Port.DESIRED_STATE), "Unexpected state");
}
@Test
@@ -339,56 +284,50 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
private void virtualHostEntryQuiescedStatusTestImpl(boolean mmQuiesceVhosts)
{
- UUID virtualHostNodeId = UUID.randomUUID();
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(VirtualHostNode.TYPE, "JSON");
-
- final ConfiguredObjectRecord virtualHostNodeRecord = new ConfiguredObjectRecordImpl(virtualHostNodeId, VirtualHostNode.class.getSimpleName(), attributes, Collections.singletonMap(Broker.class.getSimpleName(), _root.getId()));
- final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class);
- doAnswer(
- new Answer()
- {
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable
- {
- ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue();
- recoverer.handle(_root);
- recoverer.handle(_portEntry);
- recoverer.handle(virtualHostNodeRecord);
- return false;
- }
- }
- ).when(_store).openConfigurationStore(recovererArgumentCaptor.capture());
-
- State expectedState = mmQuiesceVhosts ? State.QUIESCED : null;
- if(mmQuiesceVhosts)
+ final UUID virtualHostNodeId = randomUUID();
+ final Map<String, Object> attributes = Map.of(VirtualHostNode.TYPE, "JSON");
+ final ConfiguredObjectRecord virtualHostNodeRecord =
+ new ConfiguredObjectRecordImpl(virtualHostNodeId, VirtualHostNode.class.getSimpleName(), attributes, Map.of(Broker.class.getSimpleName(), _root.getId()));
+ final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor =
+ ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class);
+ doAnswer(invocation ->
+ {
+ final ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue();
+ recoverer.handle(_root);
+ recoverer.handle(_portEntry);
+ recoverer.handle(virtualHostNodeRecord);
+ return false;
+ }).when(_store).openConfigurationStore(recovererArgumentCaptor.capture());
+
+ final State expectedState = mmQuiesceVhosts ? State.QUIESCED : null;
+ if (mmQuiesceVhosts)
{
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_QUIESCE_VIRTUAL_HOSTS, mmQuiesceVhosts);
}
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord nodeEntry = getEntry(records, virtualHostNodeId);
- Map<String, Object> nodeAttributes = new HashMap<String, Object>(nodeEntry.getAttributes());
- assertEquals("Unexpected state", expectedState, nodeAttributes.get(VirtualHostNode.DESIRED_STATE));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord nodeEntry = getEntry(records, virtualHostNodeId);
+ final Map<String, Object> nodeAttributes = new HashMap<>(nodeEntry.getAttributes());
+ assertEquals(expectedState, nodeAttributes.get(VirtualHostNode.DESIRED_STATE), "Unexpected state");
nodeAttributes.remove(VirtualHostNode.DESIRED_STATE);
- assertEquals("Unexpected attributes", attributes, nodeAttributes);
+ assertEquals(attributes, nodeAttributes, "Unexpected attributes");
}
@SuppressWarnings("unchecked")
private void assertCLIPortEntry(final Collection<ConfiguredObjectRecord> records,
- ConfiguredObjectRecord portEntry,
- UUID optionsPort,
- Protocol protocol)
+ final ConfiguredObjectRecord portEntry,
+ final UUID optionsPort,
+ final Protocol protocol)
{
- assertEquals("Unexpected entry id", optionsPort, portEntry.getId());
- assertTrue("Unexpected children", getChildrenIds(records, portEntry).isEmpty());
- Map<String, Object> attributes = portEntry.getAttributes();
- assertEquals("Unexpected name", "MANAGEMENT-MODE-PORT-" + protocol.name(), attributes.get(Port.NAME));
- assertEquals("Unexpected protocol", Collections.singleton(protocol), new HashSet<Protocol>(
- (Collection<Protocol>) attributes.get(Port.PROTOCOLS)));
+ assertEquals(optionsPort, portEntry.getId(), "Unexpected entry id");
+ assertTrue(getChildrenIds(records, portEntry).isEmpty(), "Unexpected children");
+ final Map<String, Object> attributes = portEntry.getAttributes();
+ assertEquals("MANAGEMENT-MODE-PORT-" + protocol.name(), attributes.get(Port.NAME),
+ "Unexpected name");
+ assertIterableEquals(Set.of(protocol), (Collection<Protocol>) attributes.get(Port.PROTOCOLS),
+ "Unexpected protocol");
}
@Test
@@ -397,13 +336,11 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Port.NAME, "TEST");
- ConfiguredObjectRecord
- configurationEntry = new ConfiguredObjectRecordImpl(_portEntryId, Port.class.getSimpleName(), attributes,
- Collections.singletonMap(Broker.class.getSimpleName(), getRootEntry(records).getId()));
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final Map<String, Object> attributes = Map.of(Port.NAME, "TEST");
+ final ConfiguredObjectRecord configurationEntry =
+ new ConfiguredObjectRecordImpl(_portEntryId, Port.class.getSimpleName(), attributes,
+ Map.of(Broker.class.getSimpleName(), getRootEntry(records).getId()));
_handler.create(configurationEntry);
verify(_store).create(any(ConfiguredObjectRecord.class));
}
@@ -414,13 +351,11 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- ConfiguredObjectRecord root = getRootEntry(records);
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Broker.NAME, "TEST");
- ConfiguredObjectRecord
- configurationEntry = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), attributes,root.getParents());
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final ConfiguredObjectRecord root = getRootEntry(records);
+ final Map<String, Object> attributes = Map.of(Broker.NAME, "TEST");
+ final ConfiguredObjectRecord configurationEntry =
+ new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), attributes,root.getParents());
_handler.update(false, configurationEntry);
verify(_store).update(anyBoolean(), any(ConfiguredObjectRecord.class));
}
@@ -431,24 +366,14 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- UUID portId = getOptionsPortId(records);
- Map<String, Object> attributes = new HashMap<String, Object>();
- attributes.put(Port.NAME, "TEST");
- ConfiguredObjectRecord
- configurationEntry = new ConfiguredObjectRecordImpl(portId, Port.class.getSimpleName(), attributes,
- Collections.singletonMap(Broker.class.getSimpleName(),
- getRootEntry(records).getId()));
- try
- {
- _handler.update(false, configurationEntry);
- fail("Exception should be thrown on trying to save CLI port");
- }
- catch (IllegalConfigurationException e)
- {
- // pass
- }
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final UUID portId = getOptionsPortId(records);
+ final Map<String, Object> attributes = Map.of(Port.NAME, "TEST");
+ final ConfiguredObjectRecord configurationEntry =
+ new ConfiguredObjectRecordImpl(portId, Port.class.getSimpleName(), attributes,
+ Map.of(Broker.class.getSimpleName(), getRootEntry(records).getId()));
+ assertThrows(IllegalConfigurationException.class, () -> _handler.update(false, configurationEntry),
+ "Exception should be thrown on trying to save CLI port");
}
@Test
@@ -457,9 +382,9 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ openAndGetRecords();
- ConfiguredObjectRecord record = new ConfiguredObjectRecord()
+ final ConfiguredObjectRecord record = new ConfiguredObjectRecord()
{
@Override
public UUID getId()
@@ -476,7 +401,7 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
@Override
public Map<String, Object> getAttributes()
{
- return Collections.emptyMap();
+ return Map.of();
}
@Override
@@ -495,33 +420,21 @@ public class ManagementModeStoreHandlerTest extends UnitTestBase
_systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000);
_handler = createManagementModeStoreHandler();
_handler.init(_systemConfig);
- Collection<ConfiguredObjectRecord> records = openAndGetRecords();
-
- UUID portId = getOptionsPortId(records);
- ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class);
+ final Collection<ConfiguredObjectRecord> records = openAndGetRecords();
+ final UUID portId = getOptionsPortId(records);
+ final ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class);
when(record.getId()).thenReturn(portId);
- try
- {
- _handler.remove(record);
- fail("Exception should be thrown on trying to remove CLI port");
- }
- catch (IllegalConfigurationException e)
- {
- // pass
- }
+
+ assertThrows(IllegalConfigurationException.class, () -> _handler.remove(record),
+ "Exception should be thrown on trying to remove CLI port");
}
private UUID getOptionsPortId(Collection<ConfiguredObjectRecord> records)
{
-
- ConfiguredObjectRecord root = getRootEntry(records);
- assertEquals("Unexpected root id", _rootId, root.getId());
- Collection<UUID> childrenIds = getChildrenIds(records, root);
-
+ final ConfiguredObjectRecord root = getRootEntry(records);
+ assertEquals(_rootId, root.getId(), "Unexpected root id");
+ final Collection<UUID> childrenIds = getChildrenIds(records, root);
childrenIds.remove(_portEntryId);
- UUID optionsPort = childrenIds.iterator().next();
- return optionsPort;
+ return childrenIds.iterator().next();
}
-
-
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java b/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java
index b4ae21a3aa..f5eea844f4 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java
@@ -30,8 +30,8 @@ import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.UUID;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.Broker;
import org.apache.qpid.server.model.ConfiguredObject;
@@ -48,7 +48,7 @@ public class StoreConfigurationChangeListenerTest extends UnitTestBase
private DurableConfigurationStore _store;
private StoreConfigurationChangeListener _listener;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_store = mock(DurableConfigurationStore.class);
@@ -59,26 +59,27 @@ public class StoreConfigurationChangeListenerTest extends UnitTestBase
public void testStateChanged()
{
notifyBrokerStarted();
- UUID id = UUID.randomUUID();
- ConfiguredObject object = mock(VirtualHost.class);
+ final UUID id = randomUUID();
+ final ConfiguredObject<?> object = mock(VirtualHost.class);
when(object.isDurable()).thenReturn(true);
when(object.getId()).thenReturn(id);
- ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class);
+ final ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class);
when(object.asObjectRecord()).thenReturn(record);
_listener.stateChanged(object, State.ACTIVE, State.DELETED);
verify(_store).remove(record);
}
@Test
+ @SuppressWarnings({"rawtypes", "unchecked"})
public void testChildAdded()
{
notifyBrokerStarted();
- Broker broker = mock(Broker.class);
+ final Broker broker = mock(Broker.class);
when(broker.getCategoryClass()).thenReturn(Broker.class);
when(broker.isDurable()).thenReturn(true);
- VirtualHost child = mock(VirtualHost.class);
+ final VirtualHost child = mock(VirtualHost.class);
when(child.getCategoryClass()).thenReturn(VirtualHost.class);
- Model model = mock(Model.class);
+ final Model model = mock(Model.class);
when(model.getChildTypes(any(Class.class))).thenReturn(Collections.<Class<? extends ConfiguredObject>>emptyList());
when(model.getParentType(eq(VirtualHost.class))).thenReturn((Class)Broker.class);
when(child.getModel()).thenReturn(model);
@@ -90,10 +91,11 @@ public class StoreConfigurationChangeListenerTest extends UnitTestBase
}
@Test
+ @SuppressWarnings({"rawtypes"})
public void testAttributeSet()
{
notifyBrokerStarted();
- Broker broker = mock(Broker.class);
+ final Broker broker = mock(Broker.class);
when(broker.getCategoryClass()).thenReturn(Broker.class);
when(broker.isDurable()).thenReturn(true);
final ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class);
@@ -107,16 +109,16 @@ public class StoreConfigurationChangeListenerTest extends UnitTestBase
{
notifyBrokerStarted();
- VirtualHostNode<?> object = mock(VirtualHostNode.class);
+ final VirtualHostNode<?> object = mock(VirtualHostNode.class);
when(object.managesChildStorage()).thenReturn(true);
- VirtualHost<?> virtualHost = mock(VirtualHost.class);
+ final VirtualHost<?> virtualHost = mock(VirtualHost.class);
_listener.childAdded(object, virtualHost);
verifyNoMoreInteractions(_store);
}
private void notifyBrokerStarted()
{
- Broker broker = mock(Broker.class);
+ final Broker<?> broker = mock(Broker.class);
_listener.stateChanged(broker, State.UNINITIALIZED, State.ACTIVE);
}
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java b/broker-core/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java
index ba891491f6..fdec980fa7 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/configuration/updater/TaskExecutorTest.java
@@ -20,12 +20,12 @@
*/
package org.apache.qpid.server.configuration.updater;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -40,9 +40,9 @@ import java.util.concurrent.atomic.AtomicReference;
import javax.security.auth.Subject;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.util.ServerScopedRuntimeException;
import org.apache.qpid.test.utils.UnitTestBase;
@@ -51,35 +51,29 @@ public class TaskExecutorTest extends UnitTestBase
{
private TaskExecutorImpl _executor;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_executor = new TaskExecutorImpl();
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
- try
- {
- _executor.stopImmediately();
- }
- finally
- {
- }
+ _executor.stopImmediately();
}
@Test
public void testGetState()
{
- assertFalse("Unexpected initial state", _executor.isRunning());
+ assertFalse(_executor.isRunning(), "Unexpected initial state");
}
@Test
public void testStart()
{
_executor.start();
- assertTrue("Unexpected started state", _executor.isRunning());
+ assertTrue(_executor.isRunning(), "Unexpected started state");
}
@Test
@@ -88,63 +82,57 @@ public class TaskExecutorTest extends UnitTestBase
_executor.start();
final CountDownLatch submitLatch = new CountDownLatch(2);
final CountDownLatch waitForCallLatch = new CountDownLatch(1);
- final BlockingQueue<Exception> submitExceptions = new LinkedBlockingQueue<Exception>();
+ final BlockingQueue<Exception> submitExceptions = new LinkedBlockingQueue<>();
- Runnable runnable = new Runnable()
+ final Runnable runnable = () ->
{
- @Override
- public void run()
+ try
{
- try
+ final Future<Void> f = _executor.submit(new NeverEndingCallable(waitForCallLatch));
+ submitLatch.countDown();
+ f.get();
+ }
+ catch (Exception e)
+ {
+ Exception exception = e;
+ if (exception instanceof ExecutionException)
{
- Future<Void> f = _executor.submit(new NeverEndingCallable(waitForCallLatch));
- submitLatch.countDown();
- f.get();
+ exception = (Exception) exception.getCause();
}
- catch (Exception e)
+ if (exception instanceof RuntimeException && exception.getCause() instanceof Exception)
{
- if (e instanceof ExecutionException)
- {
- e = (Exception) e.getCause();
- }
- if(e instanceof RuntimeException && e.getCause() instanceof Exception)
- {
- submitExceptions.add((Exception)e.getCause());
- }
- else
- {
- submitExceptions.add(e);
- }
+ submitExceptions.add((Exception) exception.getCause());
+ }
+ else
+ {
+ submitExceptions.add(exception);
}
}
};
- Thread t1 = new Thread(runnable);
+ final Thread t1 = new Thread(runnable);
t1.start();
- Thread t2 = new Thread(runnable);
+ final Thread t2 = new Thread(runnable);
t2.start();
final long timeout = 2000L;
- boolean awaitSubmissions = submitLatch.await(timeout, TimeUnit.MILLISECONDS);
- assertTrue(submitLatch.getCount() + " task(s) have not been submitted within expected time",
- awaitSubmissions);
+ final boolean awaitSubmissions = submitLatch.await(timeout, TimeUnit.MILLISECONDS);
+ assertTrue(awaitSubmissions, submitLatch.getCount() +
+ " task(s) have not been submitted within expected time");
- assertTrue("The first task has not been triggered",
- waitForCallLatch.await(timeout, TimeUnit.MILLISECONDS));
+ assertTrue(waitForCallLatch.await(timeout, TimeUnit.MILLISECONDS), "The first task has not been triggered");
_executor.stopImmediately();
- assertFalse("Unexpected stopped state", _executor.isRunning());
+ assertFalse(_executor.isRunning(), "Unexpected stopped state");
- Exception e = submitExceptions.poll(timeout, TimeUnit.MILLISECONDS);
- assertNotNull("The task execution was not interrupted or cancelled", e);
- Exception e2 = submitExceptions.poll(timeout, TimeUnit.MILLISECONDS);
- assertNotNull("The task execution was not interrupted or cancelled", e2);
+ final Exception e = submitExceptions.poll(timeout, TimeUnit.MILLISECONDS);
+ assertNotNull(e, "The task execution was not interrupted or cancelled");
+ final Exception e2 = submitExceptions.poll(timeout, TimeUnit.MILLISECONDS);
+ assertNotNull(e2, "The task execution was not interrupted or cancelled");
- final boolean condition1 = e2 instanceof CancellationException
- || e instanceof CancellationException;
- assertTrue("One of the exceptions should be CancellationException:", condition1);
- final boolean condition = e2 instanceof InterruptedException
- || e instanceof InterruptedException;
- assertTrue("One of the exceptions should be InterruptedException:", condition);
+ final boolean condition1 = e2 instanceof CancellationException || e instanceof CancellationException;
+ assertTrue(condition1, "One of the exceptions should be CancellationException:");
+ final boolean condition = e2 instanceof InterruptedException || e instanceof InterruptedException;
+ assertTrue(condition, "One of the exceptions should be InterruptedException:");
t1.join(timeout);
t2.join(timeout);
@@ -155,14 +143,14 @@ public class TaskExecutorTest extends UnitTestBase
{
_executor.start();
_executor.stop();
- assertFalse("Unexpected stopped state", _executor.isRunning());
+ assertFalse(_executor.isRunning(), "Unexpected stopped state");
}
@Test
- public void testSubmitAndWait() throws Exception
+ public void testSubmitAndWait()
{
_executor.start();
- Object result = _executor.run(new Task<String, RuntimeException>()
+ final Object result = _executor.run(new Task<String, RuntimeException>()
{
@Override
public String execute()
@@ -188,46 +176,34 @@ public class TaskExecutorTest extends UnitTestBase
return null;
}
});
- assertEquals("Unexpected task execution result", "DONE", result);
+ assertEquals("DONE", result, "Unexpected task execution result");
}
@Test
public void testSubmitAndWaitInNotAuthorizedContext()
{
_executor.start();
- Object subject = _executor.run(new SubjectRetriever());
- assertNull("Subject must be null", subject);
+ final Object subject = _executor.run(new SubjectRetriever());
+ assertNull(subject, "Subject must be null");
}
@Test
public void testSubmitAndWaitInAuthorizedContext()
{
_executor.start();
- Subject subject = new Subject();
- Object result = Subject.doAs(subject, new PrivilegedAction<Object>()
- {
- @Override
- public Object run()
- {
- return _executor.run(new SubjectRetriever());
- }
- });
- assertEquals("Unexpected subject", subject, result);
+ final Subject subject = new Subject();
+ final Object result = Subject.doAs(subject, (PrivilegedAction<Object>) () ->
+ _executor.run(new SubjectRetriever()));
+ assertEquals(subject, result, "Unexpected subject");
}
@Test
public void testSubmitAndWaitInAuthorizedContextWithNullSubject()
{
_executor.start();
- Object result = Subject.doAs(null, new PrivilegedAction<Object>()
- {
- @Override
- public Object run()
- {
- return _executor.run(new SubjectRetriever());
- }
- });
- assertEquals("Unexpected subject", null, result);
+ final Object result = Subject.doAs(null, (PrivilegedAction<Object>) () ->
+ _executor.run(new SubjectRetriever()));
+ assertNull(result, "Unexpected subject");
}
@Test
@@ -235,15 +211,53 @@ public class TaskExecutorTest extends UnitTestBase
{
final RuntimeException exception = new RuntimeException();
_executor.start();
- try
+ final Exception thrown = assertThrows(Exception.class,
+ () -> _executor.run(new Task<Void, RuntimeException>()
+ {
+
+ @Override
+ public Void execute()
+ {
+ throw exception;
+ }
+
+ @Override
+ public String getObject()
+ {
+ return getTestName();
+ }
+
+ @Override
+ public String getAction()
+ {
+ return "test";
+ }
+
+ @Override
+ public String getArguments()
+ {
+ return null;
+ }
+ }),
+ "Exception is expected");
+ assertEquals(exception, thrown, "Unexpected exception");
+ }
+
+ @Test
+ public void testSubmitAndWaitCurrentActorAndSecurityManagerSubjectAreRespected()
+ {
+ _executor.start();
+ final Subject subject = new Subject();
+ final AtomicReference<Subject> taskSubject = new AtomicReference<>();
+ Subject.doAs(subject, (PrivilegedAction<Object>) () ->
{
_executor.run(new Task<Void, RuntimeException>()
{
-
@Override
public Void execute()
{
- throw exception;
+ taskSubject.set(Subject.getSubject(AccessController.getContext()));
+ return null;
}
@Override
@@ -264,57 +278,10 @@ public class TaskExecutorTest extends UnitTestBase
return null;
}
});
- fail("Exception is expected");
- }
- catch (Exception e)
- {
- assertEquals("Unexpected exception", exception, e);
- }
- }
-
- @Test
- public void testSubmitAndWaitCurrentActorAndSecurityManagerSubjectAreRespected() throws Exception
- {
- _executor.start();
- Subject subject = new Subject();
- final AtomicReference<Subject> taskSubject = new AtomicReference<Subject>();
- Subject.doAs(subject, new PrivilegedAction<Object>()
- {
- @Override
- public Object run()
- {
- _executor.run(new Task<Void, RuntimeException>()
- {
- @Override
- public Void execute()
- {
- taskSubject.set(Subject.getSubject(AccessController.getContext()));
- return null;
- }
-
- @Override
- public String getObject()
- {
- return getTestName();
- }
-
- @Override
- public String getAction()
- {
- return "test";
- }
-
- @Override
- public String getArguments()
- {
- return null;
- }
- });
- return null;
- }
+ return null;
});
- assertEquals("Unexpected security manager subject", subject, taskSubject.get());
+ assertEquals(subject, taskSubject.get(), "Unexpected security manager subject");
}
private class SubjectRetriever implements Task<Subject, RuntimeException>
diff --git a/broker-core/src/test/java/org/apache/qpid/server/connection/ConnectionVersionValidatorTest.java b/broker-core/src/test/java/org/apache/qpid/server/connection/ConnectionVersionValidatorTest.java
index 1de9b25f0d..0cf2f0575a 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/connection/ConnectionVersionValidatorTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/connection/ConnectionVersionValidatorTest.java
@@ -20,8 +20,8 @@
*/
package org.apache.qpid.server.connection;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
@@ -31,14 +31,11 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Type;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.logging.EventLogger;
import org.apache.qpid.server.logging.LogMessage;
@@ -50,40 +47,41 @@ import org.apache.qpid.test.utils.UnitTestBase;
public class ConnectionVersionValidatorTest extends UnitTestBase
{
-
- private QueueManagingVirtualHost _virtualHostMock;
- private AMQPConnection _connectionMock;
+ private QueueManagingVirtualHost<?> _virtualHostMock;
+ private AMQPConnection<?> _connectionMock;
private EventLogger _eventLoggerMock;
private ConnectionVersionValidator _connectionValidator;
- @Before
+ @BeforeEach
+ @SuppressWarnings({"rawtypes", "unchecked"})
public void setUp() throws Exception
{
-
_connectionValidator = new ConnectionVersionValidator();
_virtualHostMock = mock(QueueManagingVirtualHost.class);
_connectionMock = mock(AMQPConnection.class);
_eventLoggerMock = mock(EventLogger.class);
- Broker brokerMock = mock(Broker.class);
+ final Broker brokerMock = mock(Broker.class);
when(_virtualHostMock.getBroker()).thenReturn(brokerMock);
when(brokerMock.getEventLogger()).thenReturn(_eventLoggerMock);
}
- private void setContextValues(Map<String, List<String>> values)
+ @SuppressWarnings("unchecked")
+ private void setContextValues(final Map<String, List<String>> values)
{
when(_virtualHostMock.getContextKeys(anyBoolean())).thenReturn(values.keySet());
- for (Map.Entry<String, List<String>> entry : values.entrySet())
+ for (final Map.Entry<String, List<String>> entry : values.entrySet())
{
- when(_virtualHostMock.getContextValue(any(Class.class), any(Type.class), eq(entry.getKey()))).thenReturn(entry.getValue());
+ when(_virtualHostMock.getContextValue(any(Class.class), any(Type.class), eq(entry.getKey())))
+ .thenReturn(entry.getValue());
}
}
@Test
public void testInvalidRegex()
{
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("${}", "foo"));
+ final Map<String, List<String>> contextValues = Map.of(
+ ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of("${}", "foo"));
setContextValues(contextValues);
when(_connectionMock.getClientVersion()).thenReturn("foo");
assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
@@ -107,8 +105,7 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
@Test
public void testEmptyList()
{
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Collections.<String>emptyList());
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of());
setContextValues(contextValues);
when(_connectionMock.getClientVersion()).thenReturn("foo");
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
@@ -118,8 +115,7 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
@Test
public void testEmptyString()
{
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList(""));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of(""));
setContextValues(contextValues);
when(_connectionMock.getClientVersion()).thenReturn("");
assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
@@ -134,8 +130,7 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
public void testClientRejected()
{
when(_connectionMock.getClientVersion()).thenReturn("foo");
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of("foo"));
setContextValues(contextValues);
assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT("foo"));
@@ -145,8 +140,7 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
public void testClientLogged()
{
when(_connectionMock.getClientVersion()).thenReturn("foo");
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, List.of("foo"));
setContextValues(contextValues);
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo"));
@@ -156,10 +150,9 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
public void testAllowedTakesPrecedence()
{
when(_connectionMock.getClientVersion()).thenReturn("foo");
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo"));
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo"));
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, List.of("foo"),
+ ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, List.of("foo"),
+ ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of("foo"));
setContextValues(contextValues);
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
verify(_eventLoggerMock, never()).message(any(LogMessage.class));
@@ -169,9 +162,8 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
public void testLoggedTakesPrecedenceOverRejected()
{
when(_connectionMock.getClientVersion()).thenReturn("foo");
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo"));
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, List.of("foo"),
+ ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, List.of("foo"));
setContextValues(contextValues);
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo"));
@@ -180,9 +172,8 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
@Test
public void testRegex()
{
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo"));
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("f.*"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, List.of("foo"),
+ ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, List.of("f.*"));
setContextValues(contextValues);
when(_connectionMock.getClientVersion()).thenReturn("foo");
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
@@ -198,9 +189,8 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
@Test
public void testRegexLists()
{
- Map<String, List<String>> contextValues = new HashMap<>();
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo"));
- contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("f.*", "baz"));
+ final Map<String, List<String>> contextValues = Map.of(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, List.of("foo"),
+ ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, List.of("f.*", "baz"));
setContextValues(contextValues);
when(_connectionMock.getClientVersion()).thenReturn("foo");
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
@@ -212,5 +202,4 @@ public class ConnectionVersionValidatorTest extends UnitTestBase
assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock));
verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("baz"));
}
-
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/consumer/AbstractConsumerTargetTest.java b/broker-core/src/test/java/org/apache/qpid/server/consumer/AbstractConsumerTargetTest.java
index e7f596c682..f28a8afa96 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/consumer/AbstractConsumerTargetTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/consumer/AbstractConsumerTargetTest.java
@@ -20,9 +20,9 @@
package org.apache.qpid.server.consumer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
@@ -33,8 +33,9 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
import org.mockito.InOrder;
import org.apache.qpid.server.message.MessageContainer;
@@ -56,58 +57,53 @@ import org.apache.qpid.test.utils.UnitTestBase;
public class AbstractConsumerTargetTest extends UnitTestBase
{
private final AMQPConnection<?> _connection = mock(AMQPConnection.class);
+ @SuppressWarnings("unchecked")
private final AMQPSession<?,TestAbstractConsumerTarget> _session = mock(AMQPSession.class);
private TestAbstractConsumerTarget _consumerTarget;
- private Consumer _consumer;
+ private Consumer<?, ?> _consumer;
private MessageSource _messageSource;
private MessageInstance _messageInstance;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
- when(_connection.getContextValue(eq(Long.class),
- eq(Consumer.SUSPEND_NOTIFICATION_PERIOD))).thenReturn(1000000L);
+ when(_connection.getContextValue(eq(Long.class), eq(Consumer.SUSPEND_NOTIFICATION_PERIOD))).thenReturn(1000000L);
_consumer = mock(Consumer.class);
_messageSource = mock(MessageSource.class);
- when(_messageSource.getMessageConversionExceptionHandlingPolicy()).thenReturn(MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE);
+ when(_messageSource.getMessageConversionExceptionHandlingPolicy())
+ .thenReturn(MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE);
_messageInstance = mock(MessageInstance.class);
when(_messageInstance.getOwningResource()).thenReturn(_messageSource);
- final MessageContainer messageContainer =
- new MessageContainer(_messageInstance, mock(MessageReference.class));
+ final MessageContainer messageContainer = new MessageContainer(_messageInstance, mock(MessageReference.class));
when(_consumer.pullMessage()).thenReturn(messageContainer);
_consumerTarget = new TestAbstractConsumerTarget();
_consumerTarget.consumerAdded(_consumer);
}
@Test
- public void testClose() throws Exception
+ public void testClose()
{
_consumerTarget = new TestAbstractConsumerTarget();
- assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size());
+ assertEquals(0, (long) _consumerTarget.getConsumers().size(), "Unexpected number of consumers");
_consumerTarget.consumerAdded(_consumer);
- assertEquals("Unexpected number of consumers after add",
- (long) 1,
- (long) _consumerTarget.getConsumers().size());
-
+ assertEquals(1, (long) _consumerTarget.getConsumers().size(), "Unexpected number of consumers after add");
_consumerTarget.close();
- assertEquals("Unexpected number of consumers after close",
- (long) 0,
- (long) _consumerTarget.getConsumers().size());
+ assertEquals(0, (long) _consumerTarget.getConsumers().size(), "Unexpected number of consumers after close");
verify(_consumer, times(1)).close();
}
@Test
- public void testNotifyWork() throws Exception
+ public void testNotifyWork()
{
- InOrder order = inOrder(_consumer);
+ final InOrder order = inOrder(_consumer);
_consumerTarget = new TestAbstractConsumerTarget();
- assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size());
+ assertEquals(0, (long) _consumerTarget.getConsumers().size(), "Unexpected number of consumers");
_consumerTarget.consumerAdded(_consumer);
@@ -131,106 +127,93 @@ public class AbstractConsumerTargetTest extends UnitTestBase
}
@Test
- public void testConversionExceptionPolicyClose() throws Exception
+ @SuppressWarnings("unchecked")
+ public void testConversionExceptionPolicyClose()
{
configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE);
- try
- {
- _consumerTarget.sendNextMessage();
- fail("exception not thrown");
- }
- catch (ConnectionScopedRuntimeException e)
- {
- final boolean condition = e.getCause() instanceof MessageConversionException;
- assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
- e.getCause().getClass().getSimpleName()), condition);
- }
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ final ConnectionScopedRuntimeException thrown = assertThrows(ConnectionScopedRuntimeException.class,
+ () -> _consumerTarget.sendNextMessage(), "Exception not thrown");
+ final boolean condition = thrown.getCause() instanceof MessageConversionException;
+ assertTrue(condition, String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
+ thrown.getCause().getClass().getSimpleName()));
+
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any());
}
@Test
- public void testConversionExceptionPolicyCloseForNonAcquiringConsumer() throws Exception
+ @SuppressWarnings("unchecked")
+ public void testConversionExceptionPolicyCloseForNonAcquiringConsumer()
{
configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE);
- try
- {
- _consumerTarget.sendNextMessage();
- fail("exception not thrown");
- }
- catch (ConnectionScopedRuntimeException e)
- {
- final boolean condition = e.getCause() instanceof MessageConversionException;
- assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
- e.getCause().getClass().getSimpleName()), condition);
- }
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ final ConnectionScopedRuntimeException thrown = assertThrows(ConnectionScopedRuntimeException.class,
+ () -> _consumerTarget.sendNextMessage(), "Exception not thrown");
+ final boolean condition = thrown.getCause() instanceof MessageConversionException;
+ assertTrue(condition, String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
+ thrown.getCause().getClass().getSimpleName()));
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any());
}
@Test
- public void testConversionExceptionPolicyReroute() throws Exception
+ public void testConversionExceptionPolicyReroute()
{
configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.ROUTE_TO_ALTERNATE);
_consumerTarget.sendNextMessage();
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance).routeToAlternate(null, null, null);
}
@Test
- public void testConversionExceptionPolicyRerouteForNonAcquiringConsumer() throws Exception
+ @SuppressWarnings("unchecked")
+ public void testConversionExceptionPolicyRerouteForNonAcquiringConsumer()
{
configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.ROUTE_TO_ALTERNATE);
_consumerTarget.sendNextMessage();
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any());
}
@Test
- public void testConversionExceptionPolicyReject() throws Exception
+ public void testConversionExceptionPolicyReject()
{
configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.REJECT);
_consumerTarget.sendNextMessage();
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance).reject(_consumer);
verify(_messageInstance).release(_consumer);
}
@Test
- public void testConversionExceptionPolicyRejectForNonAcquiringConsumer() throws Exception
+ public void testConversionExceptionPolicyRejectForNonAcquiringConsumer()
{
configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.REJECT);
_consumerTarget.sendNextMessage();
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance).reject(_consumer);
verify(_messageInstance).release(_consumer);
}
@Test
- public void testConversionExceptionPolicyWhenOwningResourceIsNotMessageSource() throws Exception
+ @SuppressWarnings("unchecked")
+ public void testConversionExceptionPolicyWhenOwningResourceIsNotMessageSource()
{
final TransactionLogResource owningResource = mock(TransactionLogResource.class);
when(_messageInstance.getOwningResource()).thenReturn(owningResource);
- try
- {
- _consumerTarget.sendNextMessage();
- fail("exception not thrown");
- }
- catch (ConnectionScopedRuntimeException e)
- {
- final boolean condition = e.getCause() instanceof MessageConversionException;
- assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
- e.getCause().getClass().getSimpleName()), condition);
- }
- assertTrue("message credit was not restored", _consumerTarget.isCreditRestored());
+ final ConnectionScopedRuntimeException thrown = assertThrows(ConnectionScopedRuntimeException.class,
+ () -> _consumerTarget.sendNextMessage(), "Exception not thrown");
+ final boolean condition = thrown.getCause() instanceof MessageConversionException;
+ assertTrue(condition, String.format("ConnectionScopedRuntimeException has unexpected cause '%s'",
+ thrown.getCause().getClass().getSimpleName()));
+ assertTrue(_consumerTarget.isCreditRestored(), "message credit was not restored");
verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any());
}
@@ -241,6 +224,7 @@ public class AbstractConsumerTargetTest extends UnitTestBase
when(_messageSource.getMessageConversionExceptionHandlingPolicy()).thenReturn(exceptionHandlingPolicy);
}
+ @SuppressWarnings("rawtypes")
private class TestAbstractConsumerTarget extends AbstractConsumerTarget<TestAbstractConsumerTarget>
{
private boolean _creditRestored;
diff --git a/broker-core/src/test/java/org/apache/qpid/server/consumer/TestConsumerTarget.java b/broker-core/src/test/java/org/apache/qpid/server/consumer/TestConsumerTarget.java
index 743d77ff39..5796120ac8 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/consumer/TestConsumerTarget.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/consumer/TestConsumerTarget.java
@@ -37,18 +37,18 @@ import org.apache.qpid.server.model.Queue;
import org.apache.qpid.server.session.AMQPSession;
import org.apache.qpid.server.transport.AMQPConnection;
+@SuppressWarnings({"rawtypes", "unchecked"})
public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
{
- private final String tag = "mocktag";
private final Queue<?> queue = null;
private final ArrayList<MessageInstance> _messages = new ArrayList<>();
- private final AMQPSession _sessionModel = mock(AMQPSession.class);
+ private final AMQPSession<?, ?> _sessionModel = mock(AMQPSession.class);
private boolean _closed = false;
- private State _state = State.OPEN;
private boolean _isActive = true;
- private MessageInstanceConsumer _consumer;
private boolean _notifyDesired;
+ private State _state = State.OPEN;
+ private MessageInstanceConsumer<?> _consumer;
public TestConsumerTarget()
{
@@ -73,7 +73,7 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
public String getName()
{
- return tag;
+ return "mocktag";
}
@Override
@@ -110,14 +110,11 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
return _isActive ;
}
-
-
public boolean isClosed()
{
return _closed;
}
-
@Override
public boolean isSuspended()
{
@@ -127,6 +124,7 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
@Override
public void restoreCredit(ServerMessage message)
{
+
}
@Override
@@ -178,7 +176,7 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
@Override
public ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub)
{
- close();
+ close();
return Futures.immediateFuture(null);
}
@@ -191,7 +189,7 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
@Override
public boolean processPending()
{
- MessageContainer messageContainer = _consumer.pullMessage();
+ final MessageContainer messageContainer = _consumer.pullMessage();
if (messageContainer == null)
{
return false;
@@ -206,10 +204,10 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
return _messages;
}
-
@Override
public void noMessagesAvailable()
{
+
}
@Override
@@ -223,7 +221,6 @@ public class TestConsumerTarget implements ConsumerTarget<TestConsumerTarget>
_isActive = isActive;
}
-
@Override
public boolean isMultiQueue()
{
diff --git a/broker-core/src/test/java/org/apache/qpid/server/exchange/DirectExchangeTest.java b/broker-core/src/test/java/org/apache/qpid/server/exchange/DirectExchangeTest.java
index 02cdd479f6..f7b5d44664 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/exchange/DirectExchangeTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/exchange/DirectExchangeTest.java
@@ -20,23 +20,21 @@
package org.apache.qpid.server.exchange;
import static org.apache.qpid.server.filter.AMQPFilterTypes.JMS_SELECTOR;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.message.AMQMessageHeader;
@@ -63,84 +61,57 @@ public class DirectExchangeTest extends UnitTestBase
private InstanceProperties _instanceProperties;
private ServerMessage<?> _messageWithNoHeaders;
- @Before
- public void setUp() throws Exception
+ @BeforeAll
+ public void beforeAll() throws Exception
{
- BrokerTestHelper.setUp();
- _vhost = BrokerTestHelper.createVirtualHost(getTestName(), this);
+ _vhost = BrokerTestHelper.createVirtualHost(getTestClassName(), this);
- Map<String,Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, "test");
- attributes.put(Exchange.DURABLE, false);
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ final Map<String,Object> attributes = Map.of(Exchange.NAME, "test",
+ Exchange.DURABLE, false,
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
_exchange = (DirectExchange<?>) _vhost.createChild(Exchange.class, attributes);
-
- _instanceProperties = mock(InstanceProperties.class);
- _messageWithNoHeaders = createTestMessage(Collections.emptyMap());
}
- @After
- public void tearDown() throws Exception
+ @BeforeEach
+ public void setUp() throws Exception
{
- try
- {
- if (_vhost != null)
- {
- _vhost.close();
- }
- }
- finally
- {
- BrokerTestHelper.tearDown();
- }
+ _instanceProperties = mock(InstanceProperties.class);
+ _messageWithNoHeaders = createTestMessage(Map.of());
}
@Test
- public void testCreationOfExchangeWithReservedExchangePrefixRejected() throws Exception
+ public void testCreationOfExchangeWithReservedExchangePrefixRejected()
{
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, "amq.wibble");
- attributes.put(Exchange.DURABLE, false);
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- try
- {
- _exchange = (DirectExchangeImpl) _vhost.createChild(Exchange.class, attributes);
- _exchange.open();
- fail("Exception not thrown");
- }
- catch (ReservedExchangeNameException rene)
- {
- // PASS
- }
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, "amq.wibble",
+ Exchange.DURABLE, false,
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ assertThrows(ReservedExchangeNameException.class, () ->
+ {
+ _exchange = (DirectExchangeImpl) _vhost.createChild(Exchange.class, attributes);
+ _exchange.open();
+ }, "Exception not thrown");
}
@Test
- public void testAmqpDirectRecreationRejected() throws Exception
+ public void testAmqpDirectRecreationRejected()
{
- DirectExchangeImpl amqpDirect = (DirectExchangeImpl) _vhost.getChildByName(Exchange.class, ExchangeDefaults.DIRECT_EXCHANGE_NAME);
+ final DirectExchangeImpl amqpDirect =
+ (DirectExchangeImpl) _vhost.getChildByName(Exchange.class, ExchangeDefaults.DIRECT_EXCHANGE_NAME);
assertNotNull(amqpDirect);
assertSame(amqpDirect, _vhost.getChildById(Exchange.class, amqpDirect.getId()));
assertSame(amqpDirect, _vhost.getChildByName(Exchange.class, amqpDirect.getName()));
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, ExchangeDefaults.DIRECT_EXCHANGE_NAME);
- attributes.put(Exchange.DURABLE, true);
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- try
- {
- _exchange = (DirectExchangeImpl) _vhost.createChild(Exchange.class, attributes);
- _exchange.open();
- fail("Exception not thrown");
- }
- catch (ReservedExchangeNameException rene)
- {
- // PASS
- }
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, ExchangeDefaults.DIRECT_EXCHANGE_NAME,
+ Exchange.DURABLE, true,
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ assertThrows(ReservedExchangeNameException.class, () ->
+ {
+ _exchange = (DirectExchangeImpl) _vhost.createChild(Exchange.class, attributes);
+ _exchange.open();
+ }, "Exception not thrown");
// QPID-6599, defect would mean that the existing exchange was removed from the in memory model.
assertSame(amqpDirect, _vhost.getChildById(Exchange.class, amqpDirect.getId()));
@@ -148,203 +119,154 @@ public class DirectExchangeTest extends UnitTestBase
}
@Test
- public void testDeleteOfExchangeSetAsAlternate() throws Exception
+ public void testDeleteOfExchangeSetAsAlternate()
{
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Queue.NAME, getTestName());
- attributes.put(Queue.DURABLE, false);
- attributes.put(Queue.ALTERNATE_BINDING, Collections.singletonMap(AlternateBinding.DESTINATION, _exchange.getName()));
+ final Map<String, Object> attributes = Map.of(Queue.NAME, getTestName(),
+ Queue.DURABLE, false,
+ Queue.ALTERNATE_BINDING, Map.of(AlternateBinding.DESTINATION, _exchange.getName()));
- Queue queue = _vhost.createChild(Queue.class, attributes);
+ Queue<?> queue = _vhost.createChild(Queue.class, attributes);
queue.open();
- assertEquals("Unexpected alternate exchange on queue", _exchange, queue.getAlternateBindingDestination());
-
+ assertEquals(_exchange, queue.getAlternateBindingDestination(), "Unexpected alternate exchange on queue");
- try
- {
- _exchange.delete();
- fail("Exchange deletion should fail with MessageDestinationIsAlternateException");
- }
- catch(MessageDestinationIsAlternateException e)
- {
- // pass
- }
+ assertThrows(MessageDestinationIsAlternateException.class,() ->_exchange.delete(),
+ "Exchange deletion should fail with MessageDestinationIsAlternateException");
- assertEquals("Unexpected effective exchange state", State.ACTIVE, _exchange.getState());
- assertEquals("Unexpected desired exchange state", State.ACTIVE, _exchange.getDesiredState());
+ assertEquals(State.ACTIVE, _exchange.getState(), "Unexpected effective exchange state");
+ assertEquals(State.ACTIVE, _exchange.getDesiredState(), "Unexpected desired exchange state");
}
@Test
public void testAlternateBindingValidationRejectsNonExistingDestination()
{
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, getTestName());
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
- String alternateBinding = "nonExisting";
- attributes.put(Exchange.ALTERNATE_BINDING,
- Collections.singletonMap(AlternateBinding.DESTINATION, alternateBinding));
-
- try
- {
- _vhost.createChild(Exchange.class, attributes);
- fail("Expected exception is not thrown");
- }
- catch (UnknownAlternateBindingException e)
- {
- assertEquals("Unexpected exception alternate binding", alternateBinding, e.getAlternateBindingName());
- }
+ final String alternateBinding = "nonExisting";
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS,
+ Exchange.ALTERNATE_BINDING, Map.of(AlternateBinding.DESTINATION, alternateBinding));
+
+ final UnknownAlternateBindingException thrown = assertThrows(UnknownAlternateBindingException.class,
+ () -> _vhost.createChild(Exchange.class, attributes),
+ "Expected exception is not thrown");
+ assertEquals(alternateBinding, thrown.getAlternateBindingName(), "Unexpected exception alternate binding");
}
@Test
public void testAlternateBindingValidationRejectsSelf()
{
- Map<String, String> alternateBinding = Collections.singletonMap(AlternateBinding.DESTINATION, _exchange.getName());
- Map<String, Object> newAttributes = Collections.singletonMap(Exchange.ALTERNATE_BINDING, alternateBinding);
- try
- {
- _exchange.setAttributes(newAttributes);
- fail("Expected exception is not thrown");
- }
- catch (IllegalConfigurationException e)
- {
- // pass
- }
+ final Map<String, String> alternateBinding = Map.of(AlternateBinding.DESTINATION, _exchange.getName());
+ final Map<String, Object> newAttributes = Map.of(Exchange.ALTERNATE_BINDING, alternateBinding);
+ assertThrows(IllegalConfigurationException.class, () -> _exchange.setAttributes(newAttributes),
+ "Expected exception is not thrown");
}
@Test
public void testDurableExchangeRejectsNonDurableAlternateBinding()
{
- Map<String, Object> dlqAttributes = new HashMap<>();
- String dlqName = getTestName() + "_DLQ";
- dlqAttributes.put(Queue.NAME, dlqName);
- dlqAttributes.put(Queue.DURABLE, false);
+ final String dlqName = getTestName() + "_DLQ";
+ final Map<String, Object> dlqAttributes = Map.of(Queue.NAME, dlqName,
+ Queue.DURABLE, false);
_vhost.createChild(Queue.class, dlqAttributes);
- Map<String, Object> exchangeAttributes = new HashMap<>();
- exchangeAttributes.put(Exchange.NAME, getTestName());
- exchangeAttributes.put(Exchange.ALTERNATE_BINDING, Collections.singletonMap(AlternateBinding.DESTINATION, dlqName));
- exchangeAttributes.put(Exchange.DURABLE, true);
- exchangeAttributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- try
- {
- _vhost.createChild(Exchange.class, exchangeAttributes);
- fail("Expected exception is not thrown");
- }
- catch (IllegalConfigurationException e)
- {
- // pass
- }
+ final Map<String, Object> exchangeAttributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.ALTERNATE_BINDING, Map.of(AlternateBinding.DESTINATION, dlqName),
+ Exchange.DURABLE, true,
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ assertThrows(IllegalConfigurationException.class, () -> _vhost.createChild(Exchange.class, exchangeAttributes),
+ "Expected exception is not thrown");
}
@Test
public void testAlternateBinding()
{
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, getTestName());
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
- attributes.put(Exchange.ALTERNATE_BINDING,
- Collections.singletonMap(AlternateBinding.DESTINATION, _exchange.getName()));
- attributes.put(Exchange.DURABLE, false);
-
- Exchange newExchange = _vhost.createChild(Exchange.class, attributes);
-
- assertEquals("Unexpected alternate binding",
- _exchange.getName(),
- newExchange.getAlternateBinding().getDestination());
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS,
+ Exchange.ALTERNATE_BINDING, Map.of(AlternateBinding.DESTINATION, _exchange.getName()),
+ Exchange.DURABLE, false);
+ final Exchange<?> newExchange = _vhost.createChild(Exchange.class, attributes);
+
+ assertEquals(_exchange.getName(), newExchange.getAlternateBinding().getDestination(),
+ "Unexpected alternate binding");
}
@Test
public void testRouteToQueue()
{
- String boundKey = "key";
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
+ final String boundKey = "key";
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
- RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, boundKey,
- _instanceProperties);
- assertFalse("Message unexpectedly routed to queue before bind", result.hasRoutes());
+ RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
+ assertFalse(result.hasRoutes(), "Message unexpectedly routed to queue before bind");
- boolean bind = _exchange.bind(queue.getName(), boundKey, Collections.emptyMap(), false);
- assertTrue("Bind operation should be successful", bind);
+ final boolean bind = _exchange.bind(queue.getName(), boundKey, Map.of(), false);
+ assertTrue(bind, "Bind operation should be successful");
result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertTrue("Message unexpectedly not routed to queue after bind", result.hasRoutes());
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue after bind");
- boolean unbind = _exchange.unbind(queue.getName(), boundKey);
- assertTrue("Unbind operation should be successful", unbind);
+ final boolean unbind = _exchange.unbind(queue.getName(), boundKey);
+ assertTrue(unbind, "Unbind operation should be successful");
result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertFalse("Message unexpectedly routed to queue after unbind", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message unexpectedly routed to queue after unbind");
}
@Test
public void testRouteToQueueWithSelector()
{
- String boundKey = "key";
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
+ final String boundKey = "key";
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
- InstanceProperties instanceProperties = mock(InstanceProperties.class);
- ServerMessage<?> matchingMessage = createTestMessage(Collections.singletonMap("prop", true));
- ServerMessage<?> unmatchingMessage = createTestMessage(Collections.singletonMap("prop", false));
+ final InstanceProperties instanceProperties = mock(InstanceProperties.class);
+ final ServerMessage<?> matchingMessage = createTestMessage(Map.of("prop", true));
+ final ServerMessage<?> unmatchingMessage = createTestMessage(Map.of("prop", false));
- boolean bind = _exchange.bind(queue.getName(), boundKey,
- Collections.singletonMap(JMS_SELECTOR.toString(), "prop = True"),
- false);
- assertTrue("Bind operation should be successful", bind);
+ final boolean bind = _exchange.bind(queue.getName(), boundKey,
+ Map.of(JMS_SELECTOR.toString(), "prop = True"), false);
+ assertTrue(bind, "Bind operation should be successful");
RoutingResult<ServerMessage<?>> result = _exchange.route(matchingMessage, boundKey, instanceProperties);
- assertTrue("Message with matching selector not routed to queue", result.hasRoutes());
+ assertTrue(result.hasRoutes(), "Message with matching selector not routed to queue");
result = _exchange.route(unmatchingMessage, boundKey, instanceProperties);
- assertFalse("Message with matching selector unexpectedly routed to queue", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message with matching selector unexpectedly routed to queue");
- boolean unbind = _exchange.unbind(queue.getName(), boundKey);
- assertTrue("Unbind operation should be successful", unbind);
+ final boolean unbind = _exchange.unbind(queue.getName(), boundKey);
+ assertTrue(unbind, "Unbind operation should be successful");
result = _exchange.route(matchingMessage, boundKey, instanceProperties);
- assertFalse("Message with matching selector unexpectedly routed to queue after unbind",
- result.hasRoutes());
-
+ assertFalse(result.hasRoutes(), "Message with matching selector unexpectedly routed to queue after unbind");
}
@Test
public void testRouteToQueueViaTwoExchanges()
{
- String boundKey = "key";
-
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, getTestName());
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- Exchange via = _vhost.createChild(Exchange.class, attributes);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
- boolean exchToViaBind = _exchange.bind(via.getName(), boundKey, Collections.emptyMap(), false);
- assertTrue("Exchange to exchange bind operation should be successful", exchToViaBind);
-
- boolean viaToQueueBind = via.bind(queue.getName(), boundKey, Collections.emptyMap(), false);
- assertTrue("Exchange to queue bind operation should be successful", viaToQueueBind);
-
- RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders,
- boundKey,
- _instanceProperties);
- assertTrue("Message unexpectedly not routed to queue", result.hasRoutes());
+ final String boundKey = "key";
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ final Exchange<?> via = _vhost.createChild(Exchange.class, attributes);
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
+ final boolean exchToViaBind = _exchange.bind(via.getName(), boundKey, Map.of(), false);
+ assertTrue(exchToViaBind, "Exchange to exchange bind operation should be successful");
+
+ final boolean viaToQueueBind = via.bind(queue.getName(), boundKey, Map.of(), false);
+ assertTrue(viaToQueueBind, "Exchange to queue bind operation should be successful");
+
+ final RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue");
}
-
@Test
public void testDestinationDeleted()
{
- String boundKey = "key";
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
+ final String boundKey = "key";
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
assertFalse(_exchange.isBound(boundKey));
assertFalse(_exchange.isBound(boundKey, queue));
assertFalse(_exchange.isBound(queue));
- _exchange.bind(queue.getName(), boundKey, Collections.emptyMap(), false);
+ _exchange.bind(queue.getName(), boundKey, Map.of(), false);
assertTrue(_exchange.isBound(boundKey));
assertTrue(_exchange.isBound(boundKey, queue));
@@ -357,13 +279,12 @@ public class DirectExchangeTest extends UnitTestBase
assertFalse(_exchange.isBound(queue));
}
- private ServerMessage<?> createTestMessage(Map<String, Object> headerValues)
+ private ServerMessage<?> createTestMessage(final Map<String, Object> headerValues)
{
- AMQMessageHeader header = mock(AMQMessageHeader.class);
+ final AMQMessageHeader header = mock(AMQMessageHeader.class);
headerValues.forEach((key, value) -> when(header.getHeader(key)).thenReturn(value));
- @SuppressWarnings("unchecked")
- ServerMessage<?> message = mock(ServerMessage.class);
+ final ServerMessage<?> message = mock(ServerMessage.class);
when(message.isResourceAcceptable(any(TransactionLogResource.class))).thenReturn(true);
when(message.getMessageHeader()).thenReturn(header);
return message;
@@ -372,150 +293,111 @@ public class DirectExchangeTest extends UnitTestBase
@Test
public void testRouteToMultipleQueues()
{
- String boundKey = "key";
- Queue<?> queue1 = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue1"));
- Queue<?> queue2 = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue2"));
+ final String boundKey = "key";
+ final Queue<?> queue1 = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue1"));
+ final Queue<?> queue2 = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue2"));
- boolean bind1 = _exchange.bind(queue1.getName(), boundKey, Collections.emptyMap(), false);
- assertTrue("Bind operation to queue1 should be successful", bind1);
+ final boolean bind1 = _exchange.bind(queue1.getName(), boundKey, Map.of(), false);
+ assertTrue(bind1, "Bind operation to queue1 should be successful");
RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertEquals("Message routed to unexpected number of queues",
- (long) 1,
- (long) result.getNumberOfRoutes());
+ assertEquals(1, (long) result.getNumberOfRoutes(), "Message routed to unexpected number of queues");
- _exchange.bind(queue2.getName(), boundKey, Collections.singletonMap(JMS_SELECTOR.toString(), "prop is null"), false);
+ _exchange.bind(queue2.getName(), boundKey, Map.of(JMS_SELECTOR.toString(), "prop is null"), false);
result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertEquals("Message routed to unexpected number of queues",
- (long) 2,
- (long) result.getNumberOfRoutes());
+ assertEquals(2, (long) result.getNumberOfRoutes(), "Message routed to unexpected number of queues");
_exchange.unbind(queue1.getName(), boundKey);
result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertEquals("Message routed to unexpected number of queues",
- (long) 1,
- (long) result.getNumberOfRoutes());
+ assertEquals(1, (long) result.getNumberOfRoutes(), "Message routed to unexpected number of queues");
_exchange.unbind(queue2.getName(), boundKey);
result = _exchange.route(_messageWithNoHeaders, boundKey, _instanceProperties);
- assertEquals("Message routed to unexpected number of queues",
- (long) 0,
- (long) result.getNumberOfRoutes());
+ assertEquals(0, (long) result.getNumberOfRoutes(), "Message routed to unexpected number of queues");
}
@Test
public void testRouteToQueueViaTwoExchangesWithReplacementRoutingKey()
{
- Map<String, Object> viaExchangeArguments = new HashMap<>();
- viaExchangeArguments.put(Exchange.NAME, "via_exchange");
- viaExchangeArguments.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- Exchange via = _vhost.createChild(Exchange.class, viaExchangeArguments);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
- boolean exchToViaBind = _exchange.bind(via.getName(),
- "key1",
- Collections.singletonMap(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key2"),
- false);
- assertTrue("Exchange to exchange bind operation should be successful", exchToViaBind);
-
- boolean viaToQueueBind = via.bind(queue.getName(), "key2", Collections.emptyMap(), false);
- assertTrue("Exchange to queue bind operation should be successful", viaToQueueBind);
-
- RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders,
- "key1",
- _instanceProperties);
- assertTrue("Message unexpectedly not routed to queue", result.hasRoutes());
+ final Map<String, Object> viaExchangeArguments = Map.of(Exchange.NAME, "via_exchange",
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ final Exchange<?> via = _vhost.createChild(Exchange.class, viaExchangeArguments);
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
+ final boolean exchToViaBind = _exchange.bind(via.getName(), "key1",
+ Map.of(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key2"), false);
+ assertTrue(exchToViaBind, "Exchange to exchange bind operation should be successful");
+
+ final boolean viaToQueueBind = via.bind(queue.getName(), "key2", Map.of(), false);
+ assertTrue(viaToQueueBind, "Exchange to queue bind operation should be successful");
+
+ final RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, "key1",
+ _instanceProperties);
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue");
}
@Test
public void testRouteToQueueViaTwoExchangesWithReplacementRoutingKeyAndFiltering()
{
- Map<String, Object> viaExchangeArguments = new HashMap<>();
- viaExchangeArguments.put(Exchange.NAME, getTestName() + "_via_exch");
- viaExchangeArguments.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- Exchange via = _vhost.createChild(Exchange.class, viaExchangeArguments);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
+ final Map<String, Object> viaExchangeArguments = Map.of(Exchange.NAME, getTestName() + "_via_exch",
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ final Exchange<?> via = _vhost.createChild(Exchange.class, viaExchangeArguments);
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
+ final Map<String, Object> exchToViaBindArguments = Map.of(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key2",
+ JMS_SELECTOR.toString(), "prop = True");
+ final boolean exchToViaBind = _exchange.bind(via.getName(), "key1", exchToViaBindArguments, false);
+ assertTrue(exchToViaBind, "Exchange to exchange bind operation should be successful");
+ final boolean viaToQueueBind = via.bind(queue.getName(), "key2", Map.of(), false);
+ assertTrue(viaToQueueBind, "Exchange to queue bind operation should be successful");
- Map<String, Object> exchToViaBindArguments = new HashMap<>();
- exchToViaBindArguments.put(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key2");
- exchToViaBindArguments.put(JMS_SELECTOR.toString(), "prop = True");
+ RoutingResult<ServerMessage<?>> result = _exchange.route(createTestMessage(Map.of("prop", true)), "key1",
+ _instanceProperties);
- boolean exchToViaBind = _exchange.bind(via.getName(),
- "key1",
- exchToViaBindArguments,
- false);
- assertTrue("Exchange to exchange bind operation should be successful", exchToViaBind);
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue");
- boolean viaToQueueBind = via.bind(queue.getName(), "key2", Collections.emptyMap(), false);
- assertTrue("Exchange to queue bind operation should be successful", viaToQueueBind);
-
- RoutingResult<ServerMessage<?>> result = _exchange.route(createTestMessage(Collections.singletonMap("prop", true)),
- "key1",
- _instanceProperties);
-
- assertTrue("Message unexpectedly not routed to queue", result.hasRoutes());
-
- result = _exchange.route(createTestMessage(Collections.singletonMap("prop", false)),
- "key1",
- _instanceProperties);
- assertFalse("Message unexpectedly routed to queue", result.hasRoutes());
+ result = _exchange.route(createTestMessage(Map.of("prop", false)), "key1", _instanceProperties);
+ assertFalse(result.hasRoutes(), "Message unexpectedly routed to queue");
}
@Test
public void testBindWithInvalidSelector()
{
final String queueName = getTestName() + "_queue";
- _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, queueName));
+ _vhost.createChild(Queue.class, Map.of(Queue.NAME, queueName));
- final Map<String, Object> bindArguments = Collections.singletonMap(JMS_SELECTOR.toString(), "foo in (");
+ final Map<String, Object> bindArguments = Map.of(JMS_SELECTOR.toString(), "foo in (");
+ assertThrows(IllegalArgumentException.class,
+ () -> _exchange.bind(queueName, queueName, bindArguments, false),
+ "Queue can be bound when invalid selector expression is supplied as part of bind arguments");
- try
- {
- _exchange.bind(queueName, queueName, bindArguments, false);
- fail("Queue can be bound when invalid selector expression is supplied as part of bind arguments");
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
-
- final ServerMessage<?> testMessage = createTestMessage(Collections.singletonMap("foo", "bar"));
+ final ServerMessage<?> testMessage = createTestMessage(Map.of("foo", "bar"));
final RoutingResult<ServerMessage<?>> result = _exchange.route(testMessage, queueName, _instanceProperties);
- assertFalse("Message is unexpectedly routed to queue", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message is unexpectedly routed to queue");
}
@Test
public void testBindWithInvalidSelectorWhenBindingExists()
{
final String queueName = getTestName() + "_queue";
- _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, queueName));
+ _vhost.createChild(Queue.class, Map.of(Queue.NAME, queueName));
- final Map<String, Object> bindArguments = Collections.singletonMap(JMS_SELECTOR.toString(), "foo in ('bar')");
+ final Map<String, Object> bindArguments = Map.of(JMS_SELECTOR.toString(), "foo in ('bar')");
final boolean isBound = _exchange.bind(queueName, queueName, bindArguments, false);
- assertTrue("Could not bind queue", isBound);
+ assertTrue(isBound, "Could not bind queue");
- final ServerMessage<?> testMessage = createTestMessage(Collections.singletonMap("foo", "bar"));
+ final ServerMessage<?> testMessage = createTestMessage(Map.of("foo", "bar"));
final RoutingResult<ServerMessage<?>> result = _exchange.route(testMessage, queueName, _instanceProperties);
- assertTrue("Message should be routed to queue", result.hasRoutes());
-
- final Map<String, Object> bindArguments2 = Collections.singletonMap(JMS_SELECTOR.toString(), "foo in (");
- try
- {
- _exchange.bind(queueName, queueName, bindArguments2, true);
- fail("Queue can be bound when invalid selector expression is supplied as part of bind arguments");
- }
- catch (IllegalArgumentException e)
- {
- // pass
- }
+ assertTrue(result.hasRoutes(), "Message should be routed to queue");
+
+ final Map<String, Object> bindArguments2 = Map.of(JMS_SELECTOR.toString(), "foo in (");
+ assertThrows(IllegalArgumentException.class,
+ () -> _exchange.bind(queueName, queueName, bindArguments2, true),
+ "Queue can be bound when invalid selector expression is supplied as part of bind arguments");
final RoutingResult<ServerMessage<?>> result2 = _exchange.route(testMessage, queueName, _instanceProperties);
- assertTrue("Message should be be possible to route using old binding", result2.hasRoutes());
+ assertTrue(result2.hasRoutes(), "Message should be be possible to route using old binding");
}
}
diff --git a/broker-core/src/test/java/org/apache/qpid/server/exchange/ExchangeStatisticsTest.java b/broker-core/src/test/java/org/apache/qpid/server/exchange/ExchangeStatisticsTest.java
index 9b9de685e1..fe4b25e25c 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/exchange/ExchangeStatisticsTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/exchange/ExchangeStatisticsTest.java
@@ -21,17 +21,17 @@
package org.apache.qpid.server.exchange;
import static org.apache.qpid.server.filter.AMQPFilterTypes.JMS_SELECTOR;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.message.AMQMessageHeader;
import org.apache.qpid.server.message.InstanceProperties;
@@ -49,12 +49,11 @@ public class ExchangeStatisticsTest extends UnitTestBase
private VirtualHost<?> _vhost;
private Exchange<?> _exchange;
- @Before
+ @BeforeEach
public void setUp() throws Exception
{
_vhost = BrokerTestHelper.createVirtualHost(getTestName(), this);
- final Map<String, Object> attributes = Map.of(
- Exchange.NAME, "test",
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, "test",
Exchange.DURABLE, false,
Exchange.TYPE, ExchangeDefaults.TOPIC_EXCHANGE_CLASS);
_exchange = _vhost.createChild(Exchange.class, attributes);
@@ -105,10 +104,10 @@ public class ExchangeStatisticsTest extends UnitTestBase
final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
boolean bind = _exchange.bind(queue.getName(), "test", Map.of(JMS_SELECTOR.toString(), "prop = True"), false);
- assertTrue("Bind operation should be successful", bind);
+ assertTrue(bind, "Bind operation should be successful");
final RoutingResult<ServerMessage<?>> result = _exchange.route(matchingMessage, "test", instanceProperties);
- assertTrue("Message with matching selector not routed to queue", result.hasRoutes());
+ assertTrue(result.hasRoutes(), "Message with matching selector not routed to queue");
assertEquals(1L, _exchange.getStatistics().get("bindingCount"));
assertEquals(0L, _exchange.getStatistics().get("bytesDropped"));
@@ -135,10 +134,10 @@ public class ExchangeStatisticsTest extends UnitTestBase
final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
boolean bind = _exchange.bind(queue.getName(), "test", Map.of(JMS_SELECTOR.toString(), "prop = True"), false);
- assertTrue("Bind operation should be successful", bind);
+ assertTrue(bind, "Bind operation should be successful");
final RoutingResult<ServerMessage<?>> result = _exchange.route(unmatchingMessage, "test", instanceProperties);
- assertFalse("Message without matching selector unexpectedly routed to queue", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message without matching selector unexpectedly routed to queue");
assertEquals(1L, _exchange.getStatistics().get("bindingCount"));
assertEquals(100L, _exchange.getStatistics().get("bytesDropped"));
diff --git a/broker-core/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java b/broker-core/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java
index ae4067a8fb..35db634389 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/exchange/FanoutExchangeTest.java
@@ -21,21 +21,20 @@
package org.apache.qpid.server.exchange;
import static org.apache.qpid.server.filter.AMQPFilterTypes.JMS_SELECTOR;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.qpid.server.message.AMQMessageHeader;
import org.apache.qpid.server.message.InstanceProperties;
@@ -56,337 +55,261 @@ public class FanoutExchangeTest extends UnitTestBase
private InstanceProperties _instanceProperties;
private ServerMessage<?> _messageWithNoHeaders;
- @Before
- public void setUp() throws Exception
+ @BeforeAll
+ public void beforeAll() throws Exception
{
+ _vhost = BrokerTestHelper.createVirtualHost(getTestClassName(), this);
+ }
- BrokerTestHelper.setUp();
- _vhost = BrokerTestHelper.createVirtualHost(getTestName(), this);
-
- Map<String,Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, "test");
- attributes.put(Exchange.DURABLE, false);
- attributes.put(Exchange.TYPE, ExchangeDefaults.FANOUT_EXCHANGE_CLASS);
+ @BeforeEach
+ public void setUp() throws Exception
+ {
+ final Map<String,Object> attributes = Map.of(Exchange.NAME, "test",
+ Exchange.DURABLE, false,
+ Exchange.TYPE, ExchangeDefaults.FANOUT_EXCHANGE_CLASS);
_exchange = (FanoutExchange<?>) _vhost.createChild(Exchange.class, attributes);
_exchange.open();
_instanceProperties = mock(InstanceProperties.class);
- _messageWithNoHeaders = createTestMessage(Collections.emptyMap());
+ _messageWithNoHeaders = createTestMessage(Map.of());
}
- @After
- public void tearDown() throws Exception
+ @AfterEach
+ public void afterEach()
{
- try
- {
- if (_vhost != null)
- {
- _vhost.close();
- }
- }
- finally
- {
- BrokerTestHelper.tearDown();
- }
+ _exchange.close();
}
@Test
- public void testRouteToQueue() throws Exception
+ public void testRouteToQueue()
{
- String bindingKey = "mybinding";
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
+ final String bindingKey = "mybinding";
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, null,
_instanceProperties);
- assertFalse("Message unexpectedly routed to queue before bind", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message unexpectedly routed to queue before bind");
- boolean bind = _exchange.bind(queue.getName(), bindingKey, Collections.emptyMap(), false);
- assertTrue("Bind operation should be successful", bind);
+ final boolean bind = _exchange.bind(queue.getName(), bindingKey, Map.of(), false);
+ assertTrue(bind, "Bind operation should be successful");
result = _exchange.route(_messageWithNoHeaders, null, _instanceProperties);
- assertTrue("Message not routed to queue after bind", result.hasRoutes());
+ assertTrue(result.hasRoutes(), "Message not routed to queue after bind");
boolean unbind = _exchange.unbind(queue.getName(), bindingKey);
- assertTrue("Unbind operation should be successful", unbind);
+ assertTrue(unbind, "Unbind operation should be successful");
result = _exchange.route(_messageWithNoHeaders, null, _instanceProperties);
- assertFalse("Message unexpectedly routed to queue after unbind", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message unexpectedly routed to queue after unbind");
}
@Test
public void testRouteToQueueWithSelector()
{
- String bindingKey = "mybinding";
-
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
- InstanceProperties instanceProperties = mock(InstanceProperties.class);
- ServerMessage<?> matchingMessage = createTestMessage(Collections.singletonMap("prop", true));
- ServerMessage<?> unmatchingMessage = createTestMessage(Collections.singletonMap("prop", false));
-
- boolean bind = _exchange.bind(queue.getName(), bindingKey,
- Collections.singletonMap(JMS_SELECTOR.toString(), "prop = True"),
- false);
- assertTrue("Bind operation should be successful", bind);
+ final String bindingKey = "mybinding";
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
+ final InstanceProperties instanceProperties = mock(InstanceProperties.class);
+ final ServerMessage<?> matchingMessage = createTestMessage(Map.of("prop", true));
+ final ServerMessage<?> unmatchingMessage = createTestMessage(Map.of("prop", false));
+ final boolean bind = _exchange.bind(queue.getName(), bindingKey,
+ Map.of(JMS_SELECTOR.toString(), "prop = True"), false);
+ assertTrue(bind, "Bind operation should be successful");
RoutingResult<ServerMessage<?>> result = _exchange.route(matchingMessage, null, instanceProperties);
- assertTrue("Message with matching selector not routed to queue", result.hasRoutes());
+ assertTrue(result.hasRoutes(), "Message with matching selector not routed to queue");
result = _exchange.route(unmatchingMessage, null, instanceProperties);
- assertFalse("Message without matching selector unexpectedly routed to queue", result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message without matching selector unexpectedly routed to queue");
- boolean unbind = _exchange.unbind(queue.getName(), bindingKey);
- assertTrue("Unbind operation should be successful", unbind);
+ final boolean unbind = _exchange.unbind(queue.getName(), bindingKey);
+ assertTrue(unbind, "Unbind operation should be successful");
result = _exchange.route(matchingMessage, null, instanceProperties);
- assertFalse("Message with matching selector unexpectedly routed to queue after unbind",
- result.hasRoutes());
+ assertFalse(result.hasRoutes(), "Message with matching selector unexpectedly routed to queue after unbind");
}
@Test
public void testRouteToQueueViaTwoExchanges()
{
- String bindingKey = "key";
+ final String bindingKey = "key";
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.TYPE, ExchangeDefaults.FANOUT_EXCHANGE_CLASS);
+ final Exchange<?> via = _vhost.createChild(Exchange.class, attributes);
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, getTestName());
- attributes.put(Exchange.TYPE, ExchangeDefaults.FANOUT_EXCHANGE_CLASS);
+ final boolean exchToViaBind = _exchange.bind(via.getName(), bindingKey, Map.of(), false);
+ assertTrue(exchToViaBind, "Exchange to exchange bind operation should be successful");
- Exchange via = _vhost.createChild(Exchange.class, attributes);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
+ final boolean viaToQueueBind = via.bind(queue.getName(), bindingKey, Map.of(), false);
+ assertTrue(viaToQueueBind, "Exchange to queue bind operation should be successful");
- boolean exchToViaBind = _exchange.bind(via.getName(), bindingKey, Collections.emptyMap(), false);
- assertTrue("Exchange to exchange bind operation should be successful", exchToViaBind);
-
- boolean viaToQueueBind = via.bind(queue.getName(), bindingKey, Collections.emptyMap(), false);
- assertTrue("Exchange to queue bind operation should be successful", viaToQueueBind);
-
- RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders,
- null,
- _instanceProperties);
- assertTrue("Message unexpectedly not routed to queue", result.hasRoutes());
+ final RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, null,
+ _instanceProperties);
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue");
}
@Test
public void testRouteToQueueViaTwoExchangesWithReplacementRoutingKey()
{
- Map<String, Object> attributes = new HashMap<>();
- attributes.put(Exchange.NAME, getTestName());
- attributes.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- Exchange via = _vhost.createChild(Exchange.class, attributes);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
- boolean exchToViaBind = _exchange.bind(via.getName(),
- "key",
- Collections.singletonMap(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key1"),
- false);
- assertTrue("Exchange to exchange bind operation should be successful", exchToViaBind);
-
- boolean viaToQueueBind = via.bind(queue.getName(), "key1", Collections.emptyMap(), false);
- assertTrue("Exchange to queue bind operation should be successful", viaToQueueBind);
-
- RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders,
- null,
- _instanceProperties);
- assertTrue("Message unexpectedly not routed to queue", result.hasRoutes());
+ final Map<String, Object> attributes = Map.of(Exchange.NAME, getTestName(),
+ Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+ final Exchange<?> via = _vhost.createChild(Exchange.class, attributes);
+ final Queue<?> queue = _vhost.createChild(Queue.class, Map.of(Queue.NAME, getTestName() + "_queue"));
+ final boolean exchToViaBind = _exchange.bind(via.getName(),"key",
+ Map.of(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key1"), false);
+ assertTrue(exchToViaBind, "Exchange to exchange bind operation should be successful");
+
+ final boolean viaToQueueBind = via.bind(queue.getName(), "key1", Map.of(), false);
+ assertTrue(viaToQueueBind, "Exchange to queue bind operation should be successful");
+
+ final RoutingResult<ServerMessage<?>> result = _exchange.route(_messageWithNoHeaders, null,
+ _instanceProperties);
+ assertTrue(result.hasRoutes(), "Message unexpectedly not routed to queue");
}
@Test
public void testRouteToQueueViaTwoExchangesWithReplacementRoutingKeyAndFiltering()
{
- Map<String, Object> viaExchangeArguments = new HashMap<>();
- viaExchangeArguments.put(Exchange.NAME, getTestName() + "_via_exch");
- viaExchangeArguments.put(Exchange.TYPE, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
-
- Exchange via = _vhost.createChild(Exchange.class, viaExchangeArguments);
- Queue<?> queue = _vhost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, getTestName() + "_queue"));
-
-
- Map<String, Object> exchToViaBindArguments = new HashMap<>();
- exchToViaBindArguments.put(Binding.BINDING_ARGUMENT_REPLACEMENT_ROUTING_KEY, "key2");
- exchToViaBindArguments.put(JMS_SELECTOR.toString(), "prop = True");
... 91512 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org