From 8231e856c2718e9d1fee586f552eb9e34e98d77a Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Wed, 14 Oct 2015 09:54:11 -0400 Subject: [PATCH] Remove and ban @Test Original commit: elastic/x-pack-elasticsearch@02425ca13d77d6986c93e149e51b93e87ffd2259 --- .../marvel/MarvelPluginClientTests.java | 5 - .../marvel/MarvelPluginTests.java | 15 +- .../cluster/ClusterInfoCollectorTests.java | 10 +- .../cluster/ClusterStateCollectorTests.java | 11 +- .../cluster/ClusterStatsCollectorTests.java | 9 +- .../indices/IndexRecoveryCollectorTests.java | 13 +- .../indices/IndexStatsCollectorTests.java | 12 +- .../node/NodeStatsCollectorTests.java | 9 +- .../shards/ShardsCollectorTests.java | 12 +- .../marvel/agent/exporter/ExportersTests.java | 89 ++++---- .../exporter/http/HttpExporterTests.java | 9 +- .../exporter/http/HttpExporterUtilsTests.java | 8 - .../exporter/local/LocalExporterTests.java | 23 +- .../renderer/cluster/ClusterInfoTests.java | 9 +- .../cluster/ClusterStateRendererTests.java | 3 - .../renderer/cluster/ClusterStateTests.java | 4 - .../cluster/ClusterStatsRendererTests.java | 3 - .../renderer/cluster/ClusterStatsTests.java | 4 - .../indices/IndexRecoveryRendererTests.java | 3 - .../renderer/indices/IndexRecoveryTests.java | 3 - .../indices/IndexStatsRendererTests.java | 3 - .../renderer/indices/IndexStatsTests.java | 3 - .../indices/IndicesStatsRendererTests.java | 5 - .../renderer/indices/IndicesStatsTests.java | 3 - .../renderer/node/NodeStatsRendererTests.java | 3 - .../agent/renderer/node/NodeStatsTests.java | 4 - .../renderer/shards/ShardsRendererTests.java | 4 - .../agent/renderer/shards/ShardsTests.java | 9 +- .../agent/settings/MarvelSettingTests.java | 6 - .../agent/settings/MarvelSettingsTests.java | 8 - .../license/LicenseIntegrationTests.java | 10 +- .../shield/audit/IndexAuditIT.java | 3 - .../shield/qa/ShieldTransportClientIT.java | 8 +- .../example/realm/CustomRealmIT.java | 8 +- .../example/realm/CustomRealmTests.java | 8 +- .../shield/TribeRestTestCase.java | 19 +- .../WatcherWithShieldInsufficientRoleIT.java | 4 - .../WatcherWithShieldInsufficientRoleIT.java | 4 - .../integration/ClearRealmsCacheTests.java | 21 +- .../integration/LicensingTests.java | 15 +- .../MultipleIndicesPermissionsTests.java | 6 - .../PermissionPrecedenceTests.java | 4 - .../integration/ScrollIdSigningTests.java | 13 +- .../SearchGetAndSuggestPermissionsTests.java | 8 +- .../integration/SettingsFilterTests.java | 5 +- .../ShieldCachePermissionTests.java | 4 - .../integration/ShieldClearScrollTests.java | 4 - .../integration/ldap/GroupMappingTests.java | 4 - .../ldap/MultiGroupMappingTests.java | 3 - .../ShieldPluginEnabledDisabledTests.java | 9 +- .../shield/ShieldPluginSettingsTests.java | 8 - .../shield/ShieldPluginTests.java | 7 +- .../org/elasticsearch/shield/UserTests.java | 14 +- .../shield/VersionCompatibilityTests.java | 4 - .../action/ShieldActionFilterTests.java | 22 +- .../action/ShieldActionMapperTests.java | 7 - .../shield/audit/AuditTrailModuleTests.java | 11 +- .../shield/audit/AuditTrailServiceTests.java | 23 +- .../audit/index/IndexAuditLevelTests.java | 9 +- .../index/IndexAuditTrailEnabledTests.java | 4 - .../audit/index/IndexAuditTrailTests.java | 203 ++++++++++-------- .../IndexAuditTrailUpdateMappingTests.java | 10 +- .../RemoteIndexAuditTrailStartingTests.java | 8 +- .../audit/logfile/LoggingAuditTrailTests.java | 48 ++--- .../authc/AnonymousUserHolderTests.java | 13 +- .../shield/authc/AnonymousUserTests.java | 9 +- .../authc/AuthenticationModuleTests.java | 13 +- .../InternalAuthenticationServiceTests.java | 121 +++++------ .../shield/authc/RealmsTests.java | 30 +-- .../shield/authc/RunAsIntegTests.java | 11 +- .../ActiveDirectoryGroupsResolverTests.java | 14 +- .../ActiveDirectoryRealmTests.java | 27 +-- .../ActiveDirectorySessionFactoryTests.java | 32 ++- .../authc/esusers/ESUsersRealmTests.java | 17 +- .../esusers/FileUserRolesStoreTests.java | 55 +++-- .../authc/esusers/tool/ESUsersToolTests.java | 156 ++++++-------- .../shield/authc/ldap/LdapRealmTests.java | 31 ++- .../authc/ldap/LdapSessionFactoryTests.java | 25 +-- .../LdapUserSearchSessionFactoryTests.java | 45 ++-- .../shield/authc/ldap/OpenLdapTests.java | 6 - .../authc/ldap/SearchGroupsResolverTests.java | 18 +- .../UserAttributeGroupsResolverTests.java | 12 +- .../authc/ldap/support/LDAPServersTests.java | 32 +-- .../ldap/support/SessionFactoryTests.java | 20 +- .../authc/pki/PkiAuthenticationTests.java | 19 +- .../authc/pki/PkiOptionalClientAuthTests.java | 8 +- .../shield/authc/pki/PkiRealmTests.java | 46 ++-- .../PkiWithoutClientAuthenticationTests.java | 14 +- .../shield/authc/pki/PkiWithoutSSLTests.java | 4 - .../shield/authc/support/BCryptTests.java | 4 - .../CachingUsernamePasswordRealmTests.java | 19 +- .../shield/authc/support/HasherTests.java | 18 +- .../authc/support/SecuredStringTests.java | 12 +- .../support/UsernamePasswordTokenTests.java | 26 +-- .../shield/authz/AnalyzeTests.java | 4 - .../shield/authz/IndexAliasesTests.java | 32 +-- .../InternalAuthorizationServiceTests.java | 39 ++-- .../shield/authz/PermissionTests.java | 15 +- .../shield/authz/PrivilegeTests.java | 75 +++---- .../shield/authz/SystemRoleTests.java | 3 - .../DefaultIndicesResolverTests.java | 152 +++++++------ ...cesAndAliasesResolverIntegrationTests.java | 72 ++++--- .../authz/store/FileRolesStoreTests.java | 10 - .../crypto/InternalCryptoServiceTests.java | 37 +--- .../crypto/tool/SystemKeyToolTests.java | 18 +- .../shield/rest/ShieldRestFilterTests.java | 15 +- .../shield/ssl/ClientSSLServiceTests.java | 64 +++--- .../shield/ssl/SSLSettingsTests.java | 20 +- .../shield/ssl/ServerSSLServiceTests.java | 74 ++++--- .../shield/support/AutomatonsTests.java | 16 +- .../shield/support/ShieldFilesTests.java | 15 +- .../shield/support/ValidationTests.java | 32 +-- .../transport/ClientTransportFilterTests.java | 3 - ...ServerTransportFilterIntegrationTests.java | 4 - .../transport/ServerTransportFilterTests.java | 16 +- .../transport/TransportFilterTests.java | 26 ++- .../transport/filter/IPFilterTests.java | 25 +-- .../filter/IpFilteringIntegrationTests.java | 9 +- .../filter/IpFilteringUpdateTests.java | 6 +- .../filter/ShieldIpFilterRuleTests.java | 11 +- .../netty/HandshakeWaitingHandlerTests.java | 27 ++- .../IPFilterNettyUpstreamHandlerTests.java | 54 ++++- .../netty/IPHostnameVerificationTests.java | 3 - .../ShieldNettyHttpServerTransportTests.java | 6 - .../netty/ShieldNettyTransportTests.java | 16 +- .../netty/SslHostnameVerificationTests.java | 7 +- .../transport/ssl/SslClientAuthTests.java | 23 +- .../transport/ssl/SslIntegrationTests.java | 25 ++- .../transport/ssl/SslMultiPortTests.java | 66 ++++-- .../shield/tribe/TribeShieldLoadedTests.java | 6 - .../transport/KnownActionsTests.java | 5 - .../actions/hipchat/HipChatActionFactory.java | 2 +- .../actions/slack/SlackActionFactory.java | 4 +- .../trigger/schedule/IntervalSchedule.java | 2 +- .../watcher/WatcherLifeCycleServiceTests.java | 31 ++- .../watcher/WatcherPluginDisableTests.java | 5 - .../watcher/WatcherServiceTests.java | 78 ++++--- .../actions/ActionErrorIntegrationTests.java | 14 +- .../actions/TimeThrottleIntegrationTests.java | 9 +- .../actions/email/DataAttachmentTests.java | 8 +- .../email/EmailActionIntegrationTests.java | 7 +- .../actions/email/EmailActionTests.java | 19 +- .../email/EmailSecretsIntegrationTests.java | 14 +- .../actions/email/service/AccountTests.java | 25 ++- .../actions/email/service/AccountsTests.java | 44 ++-- .../email/service/EmailTemplateTests.java | 5 +- .../actions/email/service/EmailTests.java | 5 +- .../email/service/HtmlSanitizerTests.java | 35 +-- .../service/InternalEmailServiceTests.java | 11 +- .../hipchat/HipChatActionFactoryTests.java | 37 ++-- .../actions/hipchat/HipChatActionTests.java | 20 +- .../hipchat/service/HipChatAccountsTests.java | 44 ++-- .../hipchat/service/HipChatMessageTests.java | 15 +- .../hipchat/service/HipChatServiceTests.java | 17 +- .../service/IntegrationAccountTests.java | 45 ++-- .../service/InternalHipChatServiceTests.java | 36 ++-- .../hipchat/service/UserAccountTests.java | 29 ++- .../hipchat/service/V1AccountTests.java | 29 ++- .../index/IndexActionIntegrationTests.java | 20 +- .../actions/index/IndexActionTests.java | 14 +- .../actions/logging/LoggingActionTests.java | 23 +- .../slack/SlackActionFactoryTests.java | 16 +- .../actions/slack/SlackActionTests.java | 20 +- .../slack/service/SlackAccountsTests.java | 44 ++-- .../slack/service/SlackServiceTests.java | 9 +- .../message/SlackMessageDefaultsTests.java | 4 - .../service/message/SlackMessageTests.java | 17 +- .../actions/throttler/AckThrottlerTests.java | 13 +- .../throttler/ActionThrottleTests.java | 10 - .../throttler/PeriodThrottlerTests.java | 14 +- .../throttler/WatchThrottlerTests.java | 18 +- .../actions/webhook/WebhookActionTests.java | 30 +-- .../webhook/WebhookHttpsIntegrationTests.java | 6 +- .../webhook/WebhookIntegrationTests.java | 11 +- .../always/AlwaysConditionTests.java | 21 +- .../compare/CompareConditionSearchTests.java | 14 +- .../compare/CompareConditionTests.java | 65 +++--- .../ArrayCompareConditionSearchTests.java | 3 - .../array/ArrayCompareConditionTests.java | 20 +- .../condition/never/NeverConditionTests.java | 22 +- .../script/ScriptConditionSearchTests.java | 10 +- .../script/ScriptConditionTests.java | 52 ++--- .../execution/ExecutionServiceTests.java | 22 +- .../execution/ManualExecutionTests.java | 12 +- .../TriggeredWatchStoreLifeCycleTests.java | 11 +- .../execution/TriggeredWatchStoreTests.java | 21 +- .../execution/TriggeredWatchTests.java | 5 - .../history/HistoryStoreSettingsTests.java | 6 +- .../watcher/history/HistoryStoreTests.java | 17 +- .../HistoryTemplateEmailMappingsTests.java | 4 - .../HistoryTemplateHttpMappingsTests.java | 4 +- ...storyTemplateIndexActionMappingsTests.java | 3 - ...storyTemplateSearchInputMappingsTests.java | 3 - .../HistoryTemplateTimeMappingsTests.java | 4 +- ...HistoryTemplateTransformMappingsTests.java | 3 - .../watcher/input/InputRegistryTests.java | 25 ++- .../input/http/HttpInputIntegrationTests.java | 11 +- .../watcher/input/http/HttpInputTests.java | 17 +- .../input/search/SearchInputTests.java | 16 +- .../input/simple/SimpleInputTests.java | 24 +-- .../watcher/license/LicenseTests.java | 10 - .../watcher/shield/BasicShieldTests.java | 6 - .../DynamicIndexNameIntegrationTests.java | 6 - .../watcher/support/FilterXContentTests.java | 10 +- .../watcher/support/VariablesTests.java | 3 - .../support/WatcherDateTimeUtilsTests.java | 41 ++-- .../WatcherIndexTemplateRegistryTests.java | 4 - .../watcher/support/clock/ClockTests.java | 8 +- .../concurrent/FairKeyedLockTests.java | 35 +-- .../watcher/support/http/HttpClientTests.java | 13 -- .../http/HttpConnectionTimeoutTests.java | 9 +- .../support/http/HttpReadTimeoutTests.java | 10 +- .../http/HttpRequestTemplateTests.java | 9 +- .../support/http/HttpResponseTests.java | 5 +- .../support/text/TextTemplateTests.java | 46 ++-- .../xmustache/XMustacheScriptEngineTests.java | 4 - .../text/xmustache/XMustacheTests.java | 7 - .../support/xcontent/MapPathTests.java | 17 +- .../support/xcontent/XContentSourceTests.java | 7 +- .../test/integration/BasicWatcherTests.java | 14 +- .../test/integration/BootStrapTests.java | 21 +- .../ExecutionVarsIntegrationTests.java | 6 +- .../HttpSecretsIntegrationTests.java | 12 +- .../test/integration/NoMasterNodeTests.java | 8 +- .../test/integration/WatchMetadataTests.java | 9 +- .../WatcherSettingsFilterTests.java | 5 +- .../transform/TransformIntegrationTests.java | 14 +- .../transform/chain/ChainTransformTests.java | 13 +- .../script/ScriptTransformTests.java | 38 ++-- .../search/SearchTransformTests.java | 48 +++-- .../transport/action/ack/WatchAckTests.java | 36 ++-- .../action/activate/ActivateWatchTests.java | 8 +- .../action/delete/DeleteWatchTests.java | 18 +- .../action/delete/ForceDeleteWatchTests.java | 8 +- .../action/execute/ExecuteWatchTests.java | 49 ++--- .../ExecuteWatchWithDateMathTests.java | 5 +- .../transport/action/get/GetWatchTests.java | 23 +- .../transport/action/put/PutWatchTests.java | 55 ++--- .../action/stats/SlowWatchStatsTests.java | 4 - .../action/stats/WatcherStatsTests.java | 4 - .../trigger/schedule/CronScheduleTests.java | 55 +++-- .../trigger/schedule/DailyScheduleTests.java | 87 ++++---- .../trigger/schedule/HourlyScheduleTests.java | 96 +++++---- .../schedule/IntervalScheduleTests.java | 40 ++-- .../schedule/MonthlyScheduleTests.java | 46 ++-- .../schedule/ScheduleRegistryTests.java | 25 +-- .../schedule/ScheduleTriggerEventTests.java | 7 +- .../trigger/schedule/WeeklyScheduleTests.java | 48 +++-- .../trigger/schedule/YearlyScheduleTests.java | 46 ++-- .../engine/BaseTriggerEngineTestCase.java | 18 +- .../schedule/tool/CronEvalToolTests.java | 3 - .../watcher/watch/WatchLockServiceTests.java | 27 ++- .../watcher/watch/WatchStoreTests.java | 34 ++- .../watcher/watch/WatchTests.java | 11 +- 254 files changed, 2301 insertions(+), 2892 deletions(-) diff --git a/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginClientTests.java b/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginClientTests.java index b5f70e37c1e..6a63ab08e39 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginClientTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginClientTests.java @@ -10,15 +10,12 @@ import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.Collection; import static org.hamcrest.Matchers.is; public class MarvelPluginClientTests extends ESTestCase { - - @Test public void testModulesWithClientSettings() { Settings settings = Settings.builder() .put(Client.CLIENT_TYPE_SETTING, TransportClient.CLIENT_TYPE) @@ -30,7 +27,6 @@ public class MarvelPluginClientTests extends ESTestCase { assertThat(modules.size(), is(0)); } - @Test public void testModulesWithNodeSettings() { // these settings mimic what ES does when running as a node... Settings settings = Settings.builder() @@ -41,5 +37,4 @@ public class MarvelPluginClientTests extends ESTestCase { Collection modules = plugin.nodeModules(); assertThat(modules.size(), is(6)); } - } diff --git a/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginTests.java b/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginTests.java index f4faac62f2e..eeb80729c33 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/MarvelPluginTests.java @@ -8,25 +8,17 @@ package org.elasticsearch.marvel; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.license.plugin.LicensePlugin; import org.elasticsearch.marvel.agent.AgentService; import org.elasticsearch.marvel.test.MarvelIntegTestCase; -import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.PluginInfo; -import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.tribe.TribeService; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collection; import static org.elasticsearch.test.ESIntegTestCase.Scope.TEST; import static org.hamcrest.Matchers.equalTo; @ClusterScope(scope = TEST, transportClientRatio = 0, numClientNodes = 0, numDataNodes = 0) public class MarvelPluginTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -34,21 +26,18 @@ public class MarvelPluginTests extends MarvelIntegTestCase { .build(); } - @Test public void testMarvelEnabled() { internalCluster().startNode(Settings.builder().put(MarvelPlugin.ENABLED, true).build()); assertPluginIsLoaded(); assertServiceIsBound(AgentService.class); } - @Test public void testMarvelDisabled() { internalCluster().startNode(Settings.builder().put(MarvelPlugin.ENABLED, false).build()); assertPluginIsLoaded(); assertServiceIsNotBound(AgentService.class); } - @Test public void testMarvelDisabledOnTribeNode() { internalCluster().startNode(Settings.builder().put(TribeService.TRIBE_NAME, "t1").build()); assertPluginIsLoaded(); @@ -73,7 +62,7 @@ public class MarvelPluginTests extends MarvelIntegTestCase { } } - private void assertServiceIsBound(Class klass) { + private void assertServiceIsBound(Class klass) { try { Object binding = internalCluster().getDataNodeInstance(klass); assertNotNull(binding); @@ -83,7 +72,7 @@ public class MarvelPluginTests extends MarvelIntegTestCase { } } - private void assertServiceIsNotBound(Class klass) { + private void assertServiceIsNotBound(Class klass) { try { internalCluster().getDataNodeInstance(klass); fail("should have thrown an exception about missing implementation"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterInfoCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterInfoCollectorTests.java index cb5c17872fd..a8bee4baa90 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterInfoCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterInfoCollectorTests.java @@ -13,15 +13,16 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollectorTestCase; import org.elasticsearch.marvel.agent.exporter.MarvelDoc; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; -import org.junit.Test; import java.util.Collection; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.notNullValue; public class ClusterInfoCollectorTests extends AbstractCollectorTestCase { - - @Test public void testClusterInfoCollector() throws Exception { Collection results = newClusterInfoCollector().doCollect(); assertThat(results, hasSize(1)); @@ -44,7 +45,6 @@ public class ClusterInfoCollectorTests extends AbstractCollectorTestCase { assertThat(clusterInfoMarvelDoc.getClusterStats().getNodesStats().getCounts().getTotal(), equalTo(internalCluster().getNodeNames().length)); } - @Test public void testClusterInfoCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStateCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStateCollectorTests.java index 1e4fdd4b2fa..57078392eeb 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStateCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStateCollectorTests.java @@ -13,17 +13,17 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollectorTestCase; import org.elasticsearch.marvel.agent.exporter.MarvelDoc; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; -import org.junit.Test; import java.util.Collection; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; public class ClusterStateCollectorTests extends AbstractCollectorTestCase { - - @Test public void testClusterStateCollectorNoIndices() throws Exception { Collection results = newClusterStateCollector().doCollect(); assertThat(results, hasSize(1)); @@ -42,7 +42,6 @@ public class ClusterStateCollectorTests extends AbstractCollectorTestCase { assertThat(clusterState.getRoutingTable().allShards(), hasSize(0)); } - @Test public void testClusterStateCollectorOneIndex() throws Exception { int nbShards = randomIntBetween(1, 5); assertAcked(prepareCreate("test").setSettings(Settings.settingsBuilder() @@ -77,7 +76,6 @@ public class ClusterStateCollectorTests extends AbstractCollectorTestCase { assertThat(clusterState.getRoutingTable().allShards("test"), hasSize(nbShards)); } - @Test public void testClusterStateCollectorMultipleIndices() throws Exception { int nbIndices = randomIntBetween(1, 5); int[] docsPerIndex = new int[nbIndices]; @@ -119,7 +117,6 @@ public class ClusterStateCollectorTests extends AbstractCollectorTestCase { } } - @Test public void testClusterStateCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStatsCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStatsCollectorTests.java index 790c0a74812..6cd50a6741e 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStatsCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/cluster/ClusterStatsCollectorTests.java @@ -11,15 +11,15 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollectorTestCase; import org.elasticsearch.marvel.agent.exporter.MarvelDoc; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; -import org.junit.Test; import java.util.Collection; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; public class ClusterStatsCollectorTests extends AbstractCollectorTestCase { - - @Test public void testClusterStatsCollector() throws Exception { Collection results = newClusterStatsCollector().doCollect(); assertThat(results, hasSize(1)); @@ -37,7 +37,6 @@ public class ClusterStatsCollectorTests extends AbstractCollectorTestCase { assertThat(clusterStatsMarvelDoc.getClusterStats().getNodesStats().getCounts().getTotal(), equalTo(internalCluster().getNodeNames().length)); } - @Test public void testClusterStatsCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexRecoveryCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexRecoveryCollectorTests.java index 936edf3cde4..3595cb098f2 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexRecoveryCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexRecoveryCollectorTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.marvel.agent.exporter.MarvelDoc; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.junit.Test; import java.util.Collection; import java.util.List; @@ -26,11 +25,16 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; @ClusterScope(numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class IndexRecoveryCollectorTests extends AbstractCollectorTestCase { - private final boolean activeOnly = false; private final String indexName = "test"; @@ -43,9 +47,7 @@ public class IndexRecoveryCollectorTests extends AbstractCollectorTestCase { .build(); } - @Test public void testIndexRecoveryCollector() throws Exception { - logger.info("--> start first node"); final String node1 = internalCluster().startNode(); waitForNoBlocksOnNode(node1); @@ -116,7 +118,6 @@ public class IndexRecoveryCollectorTests extends AbstractCollectorTestCase { } } - @Test public void testIndexRecoveryCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexStatsCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexStatsCollectorTests.java index 955482d7579..100bbd37481 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexStatsCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/indices/IndexStatsCollectorTests.java @@ -14,17 +14,20 @@ import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.junit.Before; -import org.junit.Test; import java.util.Collection; import java.util.Iterator; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; @ClusterScope(numClientNodes = 0) public class IndexStatsCollectorTests extends AbstractCollectorTestCase { - @Override protected int numberOfReplicas() { return 0; @@ -35,7 +38,6 @@ public class IndexStatsCollectorTests extends AbstractCollectorTestCase { waitForNoBlocksOnNodes(); } - @Test public void testIndexStatsCollectorOneIndex() throws Exception { final String indexName = "one-index"; @@ -74,7 +76,6 @@ public class IndexStatsCollectorTests extends AbstractCollectorTestCase { assertThat(indexStats.getTotal().getIndexing().getTotal().getThrottleTimeInMillis(), equalTo(0L)); } - @Test public void testIndexStatsCollectorMultipleIndices() throws Exception { final String indexPrefix = "multi-indices-"; final int nbIndices = randomIntBetween(1, 5); @@ -133,7 +134,6 @@ public class IndexStatsCollectorTests extends AbstractCollectorTestCase { } } - @Test public void testIndexStatsCollectorWithLicensing() { try { final int nbDocs = randomIntBetween(1, 20); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/node/NodeStatsCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/node/NodeStatsCollectorTests.java index ab87e04a693..4036df8c792 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/node/NodeStatsCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/node/NodeStatsCollectorTests.java @@ -18,19 +18,19 @@ import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; import org.elasticsearch.node.service.NodeService; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.junit.Test; import java.util.Collection; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; // numClientNodes is set to 0 in this test because the NodeStatsCollector never collects data on client nodes: // the NodeStatsCollector.shouldCollect() method checks if the node has node files and client nodes don't have // such files. @ClusterScope(numClientNodes = 0) public class NodeStatsCollectorTests extends AbstractCollectorTestCase { - - @Test public void testNodeStatsCollector() throws Exception { String[] nodes = internalCluster().getNodeNames(); for (String node : nodes) { @@ -57,7 +57,6 @@ public class NodeStatsCollectorTests extends AbstractCollectorTestCase { } } - @Test public void testNodeStatsCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/shards/ShardsCollectorTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/shards/ShardsCollectorTests.java index 788635b149a..45a80af7879 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/shards/ShardsCollectorTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/collector/shards/ShardsCollectorTests.java @@ -14,17 +14,18 @@ import org.elasticsearch.marvel.agent.collector.AbstractCollectorTestCase; import org.elasticsearch.marvel.agent.exporter.MarvelDoc; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.license.MarvelLicensee; -import org.junit.Test; import java.util.Collection; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; public class ShardsCollectorTests extends AbstractCollectorTestCase { - - @Test public void testShardsCollectorNoIndices() throws Exception { Collection results = newShardsCollector().doCollect(); assertThat(results, hasSize(0)); @@ -38,7 +39,6 @@ public class ShardsCollectorTests extends AbstractCollectorTestCase { .build(); } - @Test public void testShardsCollectorOneIndex() throws Exception { int nbDocs = randomIntBetween(1, 20); for (int i = 0; i < nbDocs; i++) { @@ -87,7 +87,6 @@ public class ShardsCollectorTests extends AbstractCollectorTestCase { assertThat(replicas, equalTo(expectedReplicas)); } - @Test public void testShardsCollectorMultipleIndices() throws Exception { final String indexPrefix = "test-shards-"; final int nbIndices = randomIntBetween(1, 3); @@ -154,7 +153,6 @@ public class ShardsCollectorTests extends AbstractCollectorTestCase { } } - @Test public void testShardsCollectorWithLicensing() { try { String[] nodes = internalCluster().getNodeNames(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/ExportersTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/ExportersTests.java index ba1f65b9d97..91db50c1a39 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/ExportersTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/ExportersTests.java @@ -16,19 +16,31 @@ import org.elasticsearch.marvel.shield.SecuredClient; import org.elasticsearch.node.settings.NodeSettingsService; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; /** * */ public class ExportersTests extends ESTestCase { - private Exporters exporters; private Map factories; private MarvelSettingsFilter settingsFilter; @@ -51,8 +63,7 @@ public class ExportersTests extends ESTestCase { exporters = new Exporters(Settings.EMPTY, factories, settingsFilter, clusterService, nodeSettingsService); } - @Test - public void testInitExporters_Default() throws Exception { + public void testInitExportersDefault() throws Exception { Exporter.Factory factory = new TestFactory("_type", true); factories.put("_type", factory); Exporters.CurrentExporters internalExporters = exporters.initExporters(Settings.builder() @@ -65,8 +76,7 @@ public class ExportersTests extends ESTestCase { assertThat(internalExporters.exporters.get("default_" + LocalExporter.TYPE), instanceOf(LocalExporter.class)); } - @Test - public void testInitExporters_Single() throws Exception { + public void testInitExportersSingle() throws Exception { Exporter.Factory factory = new TestFactory("_type", true); factories.put("_type", factory); Exporters.CurrentExporters internalExporters = exporters.initExporters(Settings.builder() @@ -82,8 +92,7 @@ public class ExportersTests extends ESTestCase { assertThat(internalExporters.exporters.get("_name").type, is("_type")); } - @Test - public void testInitExporters_Single_Disabled() throws Exception { + public void testInitExportersSingleDisabled() throws Exception { Exporter.Factory factory = new TestFactory("_type", true); factories.put("_type", factory); Exporters.CurrentExporters internalExporters = exporters.initExporters(Settings.builder() @@ -101,22 +110,29 @@ public class ExportersTests extends ESTestCase { assertThat(internalExporters.exporters.size(), is(0)); } - @Test(expected = SettingsException.class) - public void testInitExporters_Single_UnknownType() throws Exception { - exporters.initExporters(Settings.builder() - .put("_name.type", "unknown_type") - .build()); + public void testInitExportersSingleUnknownType() throws Exception { + try { + exporters.initExporters(Settings.builder() + .put("_name.type", "unknown_type") + .build()); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("unknown exporter type [unknown_type]")); + } } - @Test(expected = SettingsException.class) - public void testInitExporters_Single_MissingExporterType() throws Exception { - exporters.initExporters(Settings.builder() - .put("_name.foo", "bar") - .build()); + public void testInitExportersSingleMissingExporterType() throws Exception { + try { + exporters.initExporters(Settings.builder() + .put("_name.foo", "bar") + .build()); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("missing exporter type for [_name]")); + } } - @Test - public void testInitExporters_Multiple_SameType() throws Exception { + public void testInitExportersMultipleSameType() throws Exception { Exporter.Factory factory = new TestFactory("_type", false); factories.put("_type", factory); Exporters.CurrentExporters internalExporters = exporters.initExporters(Settings.builder() @@ -137,17 +153,20 @@ public class ExportersTests extends ESTestCase { assertThat(internalExporters.exporters.get("_name1").type, is("_type")); } - @Test(expected = SettingsException.class) - public void testInitExporters_Multiple_SameType_Singletons() throws Exception { + public void testInitExportersMultipleSameTypeSingletons() throws Exception { Exporter.Factory factory = new TestFactory("_type", true); factories.put("_type", factory); - exporters.initExporters(Settings.builder() - .put("_name0.type", "_type") - .put("_name1.type", "_type") - .build()); + try { + exporters.initExporters(Settings.builder() + .put("_name0.type", "_type") + .put("_name1.type", "_type") + .build()); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("multiple [_type] exporters are configured. there can only be one")); + } } - @Test public void testSettingsUpdate() throws Exception { Exporter.Factory factory = spy(new TestFactory("_type", false)); factories.put("_type", factory); @@ -188,8 +207,7 @@ public class ExportersTests extends ESTestCase { assertThat(settings, hasEntry("_name1.foo", "bar")); } - @Test - public void testOpenBulk_OnMaster() throws Exception { + public void testOpenBulkOnMaster() throws Exception { Exporter.Factory factory = new MockFactory("mock", false); Exporter.Factory masterOnlyFactory = new MockFactory("mock_master_only", true); factories.put("mock", factory); @@ -213,8 +231,7 @@ public class ExportersTests extends ESTestCase { verify(exporters.getExporter("_name1"), times(1)).openBulk(); } - @Test - public void testExport_NotOnMaster() throws Exception { + public void testExportNotOnMaster() throws Exception { Exporter.Factory factory = new MockFactory("mock", false); Exporter.Factory masterOnlyFactory = new MockFactory("mock_master_only", true); factories.put("mock", factory); @@ -239,7 +256,6 @@ public class ExportersTests extends ESTestCase { } static class TestFactory extends Exporter.Factory { - public TestFactory(String type, boolean singleton) { super(type, singleton); } @@ -250,7 +266,6 @@ public class ExportersTests extends ESTestCase { } static class TestExporter extends Exporter { - public TestExporter(String type, Config config) { super(type, config); } @@ -271,7 +286,6 @@ public class ExportersTests extends ESTestCase { } static class MockFactory extends Exporter.Factory { - private final boolean masterOnly; public MockFactory(String type, boolean masterOnly) { @@ -291,7 +305,6 @@ public class ExportersTests extends ESTestCase { } static class TestNodeSettingsService extends NodeSettingsService { - private final List listeners = new ArrayList<>(); public TestNodeSettingsService() { diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterTests.java index f95f8b3f30b..a27e0007b92 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterTests.java @@ -9,6 +9,7 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.QueueDispatcher; import com.squareup.okhttp.mockwebserver.RecordedRequest; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; @@ -32,7 +33,6 @@ import org.hamcrest.Matchers; import org.joda.time.format.DateTimeFormat; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.net.BindException; @@ -46,7 +46,6 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; @ESIntegTestCase.ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class HttpExporterTests extends MarvelIntegTestCase { - private int webPort; private MockWebServer webServer; @@ -73,7 +72,6 @@ public class HttpExporterTests extends MarvelIntegTestCase { webServer.shutdown(); } - @Test public void testExport() throws Exception { enqueueGetClusterVersionResponse(Version.CURRENT); enqueueResponse(404, "marvel template does not exist"); @@ -111,7 +109,6 @@ public class HttpExporterTests extends MarvelIntegTestCase { assertThat(recordedRequest.getPath(), equalTo("/_bulk")); } - @Test public void testDynamicHostChange() { // disable exporting to be able to use non valid hosts Settings.Builder builder = Settings.builder() @@ -136,7 +133,6 @@ public class HttpExporterTests extends MarvelIntegTestCase { assertThat(getExporter(nodeName).hosts, Matchers.arrayContaining("test3")); } - @Test public void testHostChangeReChecksTemplate() throws Exception { Settings.Builder builder = Settings.builder() @@ -237,9 +233,7 @@ public class HttpExporterTests extends MarvelIntegTestCase { } } - @Test public void testDynamicIndexFormatChange() throws Exception { - Settings.Builder builder = Settings.builder() .put(MarvelSettings.INTERVAL, "-1") .put("marvel.agent.exporters._http.type", "http") @@ -334,7 +328,6 @@ public class HttpExporterTests extends MarvelIntegTestCase { assertThat(index.get("_index"), equalTo(expectedMarvelIndex)); } - @Test public void testLoadRemoteClusterVersion() throws IOException { final String host = webServer.getHostName() + ":" + webServer.getPort(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterUtilsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterUtilsTests.java index 444401e78ca..0b1e496787a 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterUtilsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/http/HttpExporterUtilsTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.marvel.agent.exporter.MarvelTemplateUtils; import org.elasticsearch.marvel.support.VersionUtils; import org.elasticsearch.test.ESTestCase; import org.hamcrest.Matchers; -import org.junit.Test; import java.io.IOException; import java.net.MalformedURLException; @@ -24,15 +23,12 @@ import static org.hamcrest.CoreMatchers.equalTo; public class HttpExporterUtilsTests extends ESTestCase { - - @Test public void testLoadTemplate() { byte[] template = MarvelTemplateUtils.loadDefaultTemplate(); assertNotNull(template); assertThat(template.length, Matchers.greaterThan(0)); } - @Test public void testParseTemplateVersionFromByteArrayTemplate() throws IOException { byte[] template = MarvelTemplateUtils.loadDefaultTemplate(); assertNotNull(template); @@ -41,7 +37,6 @@ public class HttpExporterUtilsTests extends ESTestCase { assertNotNull(version); } - @Test public void testParseTemplateVersionFromStringTemplate() throws IOException { List templates = new ArrayList<>(); templates.add("{\"marvel_version\": \"1.4.0.Beta1\"}"); @@ -60,7 +55,6 @@ public class HttpExporterUtilsTests extends ESTestCase { assertNull(version); } - @Test public void testParseVersion() throws IOException { assertNotNull(VersionUtils.parseVersion(MARVEL_VERSION_FIELD, "{\"marvel_version\": \"2.0.0-beta1\"}")); assertNotNull(VersionUtils.parseVersion(MARVEL_VERSION_FIELD, "{\"marvel_version\": \"2.0.0\"}")); @@ -70,8 +64,6 @@ public class HttpExporterUtilsTests extends ESTestCase { assertNull(VersionUtils.parseVersion(MARVEL_VERSION_FIELD + "unkown", "{\"marvel_version\": \"1.5.2\"}")); } - - @Test public void testHostParsing() throws MalformedURLException, URISyntaxException { URL url = HttpExporterUtils.parseHostWithPath("localhost:9200", ""); verifyUrl(url, "http", "localhost", 9200, "/"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/local/LocalExporterTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/local/LocalExporterTests.java index 92b7e133825..627016ad571 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/local/LocalExporterTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/exporter/local/LocalExporterTests.java @@ -37,7 +37,6 @@ import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.InternalTestCluster; import org.joda.time.format.DateTimeFormat; import org.junit.After; -import org.junit.Test; import java.util.ArrayList; import java.util.Collections; @@ -48,12 +47,22 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.elasticsearch.marvel.agent.exporter.Exporter.MIN_SUPPORTED_TEMPLATE_VERSION; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; @ClusterScope(scope = Scope.TEST, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class LocalExporterTests extends MarvelIntegTestCase { - private final static AtomicLong timeStampGenerator = new AtomicLong(); @Override @@ -70,7 +79,6 @@ public class LocalExporterTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testSimpleExport() throws Exception { internalCluster().startNode(Settings.builder() .put("marvel.agent.exporters._local.type", LocalExporter.TYPE) @@ -103,7 +111,6 @@ public class LocalExporterTests extends MarvelIntegTestCase { } } - @Test public void testTemplateCreation() throws Exception { internalCluster().startNode(Settings.builder() .put("marvel.agent.exporters._local.type", LocalExporter.TYPE) @@ -126,7 +133,6 @@ public class LocalExporterTests extends MarvelIntegTestCase { assertThat(getCurrentlyInstalledTemplateVersion(), is(Version.CURRENT)); } - @Test public void testTemplateUpdate() throws Exception { internalCluster().startNode(Settings.builder() .put("marvel.agent.exporters._local.type", LocalExporter.TYPE) @@ -171,9 +177,7 @@ public class LocalExporterTests extends MarvelIntegTestCase { awaitMarvelTemplateInstalled(Version.CURRENT); } - @Test public void testUnsupportedTemplateVersion() throws Exception { - Exporter.Config config = new Exporter.Config("_name", Settings.EMPTY, Settings.builder() .put("type", "local").build()); Client client = mock(Client.class); @@ -209,7 +213,6 @@ public class LocalExporterTests extends MarvelIntegTestCase { verify(exporter, times(1)).installedTemplateVersionIsSufficient(Version.CURRENT, unsupportedVersion); } - @Test public void testIndexTimestampFormat() throws Exception { long time = System.currentTimeMillis(); String timeFormat = randomFrom("YY", "YYYY", "YYYY.MM", "YYYY-MM", "MM.YYYY", "MM"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoTests.java index e83142cb810..6837d7cf18c 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterInfoTests.java @@ -17,18 +17,20 @@ import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.elasticsearch.test.ESIntegTestCase.Scope.TEST; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; @ClusterScope(scope = TEST) public class ClusterInfoTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -49,7 +51,6 @@ public class ClusterInfoTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testClusterInfo() throws Exception { securedEnsureGreen(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateRendererTests.java index e5f6d97e6b4..f1a76ee4cad 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateRendererTests.java @@ -16,13 +16,10 @@ import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; public class ClusterStateRendererTests extends ESSingleNodeTestCase { - private static final String SAMPLE_FILE = "/samples/cluster_state.json"; - @Test public void testClusterStateRenderer() throws Exception { createIndex("my-index", Settings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 3) diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateTests.java index 82471feefe5..ef2d1fe00d2 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStateTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -27,7 +26,6 @@ import static org.hamcrest.Matchers.greaterThan; @ClusterScope(scope = Scope.TEST) public class ClusterStateTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -51,7 +49,6 @@ public class ClusterStateTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testClusterState() throws Exception { logger.debug("--> waiting for documents to be collected"); awaitMarvelDocsCount(greaterThan(0L), ClusterStateCollector.TYPE); @@ -77,7 +74,6 @@ public class ClusterStateTests extends MarvelIntegTestCase { * This test should fail if the mapping for the 'nodes' attribute * in the 'cluster_state' document is NOT set to 'enable: false' */ - @Test public void testNoNodesIndexing() throws Exception { logger.debug("--> waiting for documents to be collected"); awaitMarvelDocsCount(greaterThan(0L), ClusterStateCollector.TYPE); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsRendererTests.java index 3257fa15440..8f420c90569 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsRendererTests.java @@ -11,13 +11,10 @@ import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; public class ClusterStatsRendererTests extends ESSingleNodeTestCase { - private static final String SAMPLE_FILE = "/samples/cluster_stats.json"; - @Test public void testClusterStatsRenderer() throws Exception { createIndex("index-0"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsTests.java index a4b24f635bb..537c3991cea 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/cluster/ClusterStatsTests.java @@ -15,8 +15,6 @@ import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; -import org.junit.Before; -import org.junit.Test; import java.util.Locale; import java.util.Map; @@ -27,7 +25,6 @@ import static org.hamcrest.Matchers.greaterThan; @ClusterScope(scope = Scope.TEST, numClientNodes = 0) public class ClusterStatsTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -45,7 +42,6 @@ public class ClusterStatsTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testClusterStats() throws Exception { logger.debug("--> creating some indices so that every data nodes will at least a shard"); ClusterStatsNodes.Counts counts = client().admin().cluster().prepareClusterStats().get().getNodesStats().getCounts(); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryRendererTests.java index 657184f69d9..d141f9f5c53 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryRendererTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; @@ -24,10 +23,8 @@ import java.util.List; import java.util.Map; public class IndexRecoveryRendererTests extends ESTestCase { - private static final String SAMPLE_FILE = "/samples/index_recovery.json"; - @Test public void testIndexRecoveryRenderer() throws Exception { logger.debug("--> creating the index recovery marvel document"); String indexName = "index-0"; diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryTests.java index a4e31589dec..d9f56181fd5 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexRecoveryTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.junit.After; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -25,7 +24,6 @@ import static org.hamcrest.Matchers.is; @ClusterScope(scope = TEST) public class IndexRecoveryTests extends MarvelIntegTestCase { - private static final String INDEX_PREFIX = "test-index-recovery-"; @Override @@ -46,7 +44,6 @@ public class IndexRecoveryTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testIndexRecovery() throws Exception { logger.debug("--> creating some indices so that index recovery collector reports data"); for (int i = 0; i < randomIntBetween(1, 10); i++) { diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsRendererTests.java index 16f2ecce02c..1d3f701dc92 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsRendererTests.java @@ -21,13 +21,10 @@ import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; public class IndexStatsRendererTests extends ESTestCase { - private static final String SAMPLE_FILE = "/samples/index_stats.json"; - @Test public void testIndexStatsRenderer() throws Exception { logger.debug("--> creating the index stats marvel document"); IndexStatsMarvelDoc marvelDoc = new IndexStatsMarvelDoc("test", "index_stats", 1437580442979L, diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsTests.java index 68dec34c02d..c3fa7f0aea5 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndexStatsTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -24,7 +23,6 @@ import static org.hamcrest.Matchers.greaterThan; @ClusterScope(scope = Scope.TEST, numClientNodes = 0) public class IndexStatsTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -42,7 +40,6 @@ public class IndexStatsTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testIndexStats() throws Exception { logger.debug("--> creating some indices for future index stats"); final int nbIndices = randomIntBetween(1, 5); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsRendererTests.java index ed06c7e5536..35fa551feae 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsRendererTests.java @@ -6,20 +6,15 @@ package org.elasticsearch.marvel.agent.renderer.indices; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; -import org.elasticsearch.cluster.metadata.IndexMetaData; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.marvel.agent.collector.indices.IndicesStatsMarvelDoc; import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; public class IndicesStatsRendererTests extends ESSingleNodeTestCase { - private static final String SAMPLE_FILE = "/samples/indices_stats.json"; - @Test public void testIndexStatsRenderer() throws Exception { createIndex("index-0"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsTests.java index 222a437216e..c1dbe2da2e8 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/indices/IndicesStatsTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -24,7 +23,6 @@ import static org.hamcrest.Matchers.greaterThan; @ClusterScope(scope = Scope.TEST, numClientNodes = 0) public class IndicesStatsTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -42,7 +40,6 @@ public class IndicesStatsTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testIndicesStats() throws Exception { logger.debug("--> creating some indices for future indices stats"); final int nbIndices = randomIntBetween(1, 5); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsRendererTests.java index 7b8588f0c8b..582fc70042c 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsRendererTests.java @@ -12,13 +12,10 @@ import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.node.service.NodeService; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; public class NodeStatsRendererTests extends ESSingleNodeTestCase { - private static final String SAMPLE_FILE = "/samples/node_stats.json"; - @Test public void testNodeStatsRenderer() throws Exception { createIndex("index-0"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsTests.java index 889b600cfba..292035797fd 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/node/NodeStatsTests.java @@ -12,11 +12,9 @@ import org.elasticsearch.marvel.agent.exporter.local.LocalExporter; import org.elasticsearch.marvel.agent.settings.MarvelSettings; import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.search.SearchHit; -import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -25,7 +23,6 @@ import static org.hamcrest.Matchers.greaterThan; @ClusterScope(scope = Scope.TEST) public class NodeStatsTests extends MarvelIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -43,7 +40,6 @@ public class NodeStatsTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testNodeStats() throws Exception { logger.debug("--> creating some indices for future node stats"); final int numDocs = between(50, 150); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsRendererTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsRendererTests.java index 39be1bfc1cb..b433222dc55 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsRendererTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsRendererTests.java @@ -14,15 +14,12 @@ import org.elasticsearch.marvel.agent.renderer.Renderer; import org.elasticsearch.marvel.agent.renderer.RendererTestUtils; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.StreamsUtils; -import org.junit.Test; import java.io.IOException; public class ShardsRendererTests extends ESSingleNodeTestCase { - private static final String SAMPLE_FILE = "/samples/shards.json"; - @Test public void testShardsRenderer() throws Exception { createIndex("my-index", Settings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) @@ -47,7 +44,6 @@ public class ShardsRendererTests extends ESSingleNodeTestCase { RendererTestUtils.assertJSONStructure(result, expected); } - @Test public void testNoShard() throws IOException { String result = RendererTestUtils.renderAsJSON(new ShardMarvelDoc("my-index", "shards", "my-id", "cluster-uuid", 1437580442979L, null, "my-state-uuid"), new ShardsRenderer()); RendererTestUtils.assertJSONStructureAndValues(result, "{\"cluster_uuid\":\"my-cluster-uuid\",\"timestamp\":\"2015-07-22T15:54:02.979Z\",\"state_uuid\":\"my-state-uuid\"}"); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsTests.java index 8a3c2770297..45aefddace0 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/renderer/shards/ShardsTests.java @@ -20,17 +20,18 @@ import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.junit.After; -import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.instanceOf; @ClusterScope(scope = Scope.TEST) public class ShardsTests extends MarvelIntegTestCase { - private static final String INDEX_PREFIX = "test-shards-"; @Override @@ -51,7 +52,6 @@ public class ShardsTests extends MarvelIntegTestCase { wipeMarvelIndices(); } - @Test public void testShards() throws Exception { logger.debug("--> creating some indices so that shards collector reports data"); for (int i = 0; i < randomIntBetween(1, 5); i++) { @@ -87,7 +87,6 @@ public class ShardsTests extends MarvelIntegTestCase { * This test uses a terms aggregation to check that the "not_analyzed" * fields of the "shards" document type are indeed not analyzed */ - @Test public void testNotAnalyzedFields() throws Exception { final String indexName = INDEX_PREFIX + randomInt(); assertAcked(prepareCreate(indexName).setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1, IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingTests.java index e367537b095..4297a41c806 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingTests.java @@ -8,14 +8,11 @@ package org.elasticsearch.marvel.agent.settings; import org.elasticsearch.common.Strings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.Matchers.equalTo; public class MarvelSettingTests extends ESTestCase { - - @Test public void testBooleanMarvelSetting() { String name = randomAsciiOfLength(10); String description = randomAsciiOfLength(20); @@ -36,7 +33,6 @@ public class MarvelSettingTests extends ESTestCase { assertTrue(setting.getValue()); } - @Test public void testTimeValueMarvelSetting() { String name = randomAsciiOfLength(10); String description = randomAsciiOfLength(20); @@ -66,7 +62,6 @@ public class MarvelSettingTests extends ESTestCase { assertThat(setting.getValue().millis(), equalTo(updated.millis())); } - @Test public void testStringMarvelSetting() { String name = randomAsciiOfLength(10); String description = randomAsciiOfLength(20); @@ -96,7 +91,6 @@ public class MarvelSettingTests extends ESTestCase { assertThat(setting.getValue(), equalTo(updated)); } - @Test public void testStringArrayMarvelSetting() { String name = randomAsciiOfLength(10); String description = randomAsciiOfLength(20); diff --git a/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingsTests.java b/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingsTests.java index 1f58d160565..525f94b90d5 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingsTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/agent/settings/MarvelSettingsTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.node.Node; import org.elasticsearch.test.ESIntegTestCase; -import org.junit.Test; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.equalTo; @@ -19,7 +18,6 @@ import static org.hamcrest.Matchers.instanceOf; @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 1, numClientNodes = 0) public class MarvelSettingsTests extends MarvelIntegTestCase { - private final TimeValue interval = newRandomTimeValue(); private final TimeValue indexStatsTimeout = newRandomTimeValue(); private final TimeValue indicesStatsTimeout = newRandomTimeValue(); @@ -29,7 +27,6 @@ public class MarvelSettingsTests extends MarvelIntegTestCase { private final TimeValue recoveryTimeout = newRandomTimeValue(); private final Boolean recoveryActiveOnly = randomBoolean(); private final String[] collectors = randomStringArray(); - private final TimeValue licenseGracePeriod = randomExpirationDelay(); @Override protected Settings nodeSettings(int nodeOrdinal) { @@ -54,7 +51,6 @@ public class MarvelSettingsTests extends MarvelIntegTestCase { .build(); } - @Test public void testMarvelSettings() throws Exception { logger.info("--> testing marvel settings service initialization"); for (final MarvelSettings marvelSettings : internalCluster().getInstances(MarvelSettings.class)) { @@ -173,8 +169,4 @@ public class MarvelSettingsTests extends MarvelIntegTestCase { } return items; } - - private TimeValue randomExpirationDelay() { - return randomBoolean() ? newRandomTimeValue() : TimeValue.timeValueHours(randomIntBetween(-10, 10) * 24); - } } diff --git a/marvel/src/test/java/org/elasticsearch/marvel/license/LicenseIntegrationTests.java b/marvel/src/test/java/org/elasticsearch/marvel/license/LicenseIntegrationTests.java index fba46aea04d..75f52c187d2 100644 --- a/marvel/src/test/java/org/elasticsearch/marvel/license/LicenseIntegrationTests.java +++ b/marvel/src/test/java/org/elasticsearch/marvel/license/LicenseIntegrationTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.marvel.license; import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.SysGlobals; + import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Inject; @@ -21,9 +22,12 @@ import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.hamcrest.Matchers.equalTo; @@ -32,7 +36,6 @@ import static org.hamcrest.Matchers.isOneOf; @ClusterScope(scope = SUITE, transportClientRatio = 0, numClientNodes = 0) public class LicenseIntegrationTests extends MarvelIntegTestCase { - @Override protected Collection> nodePlugins() { if (shieldEnabled) { @@ -48,7 +51,6 @@ public class LicenseIntegrationTests extends MarvelIntegTestCase { .build(); } - @Test public void testEnableDisableLicense() { assertThat(getLicensee().getStatus().getLicenseState(), isOneOf(LicenseState.ENABLED, LicenseState.GRACE_PERIOD)); assertThat(getLicensee().collectionEnabled(), is(true)); diff --git a/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java b/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java index e76d3e01fbb..1c6b3bdb3a3 100644 --- a/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java +++ b/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java @@ -14,7 +14,6 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; import java.util.Collection; import java.util.Collections; @@ -24,11 +23,9 @@ import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; public class IndexAuditIT extends ESIntegTestCase { - private static final String USER = "test_user"; private static final String PASS = "changeme"; - @Test public void testShieldIndexAuditTrailWorking() throws Exception { HttpResponse response = httpClient().path("/_cluster/health") .addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))) diff --git a/qa/shield-client-tests/src/test/java/org/elasticsearch/shield/qa/ShieldTransportClientIT.java b/qa/shield-client-tests/src/test/java/org/elasticsearch/shield/qa/ShieldTransportClientIT.java index e2c6ce6adc9..3dcaa58a950 100644 --- a/qa/shield-client-tests/src/test/java/org/elasticsearch/shield/qa/ShieldTransportClientIT.java +++ b/qa/shield-client-tests/src/test/java/org/elasticsearch/shield/qa/ShieldTransportClientIT.java @@ -16,20 +16,19 @@ import org.elasticsearch.plugins.Plugin; import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.ESIntegTestCase; -import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; /** * Integration tests that test a transport client with Shield being loaded that connect to an external cluster */ public class ShieldTransportClientIT extends ESIntegTestCase { - static final String ADMIN_USER_PW = "test_user:changeme"; static final String TRANSPORT_USER_PW = "transport:changeme"; @@ -45,7 +44,6 @@ public class ShieldTransportClientIT extends ESIntegTestCase { return Collections.singletonList(ShieldPlugin.class); } - @Test public void testThatTransportClientWithoutAuthenticationDoesNotWork() throws Exception { try (TransportClient client = transportClient(Settings.EMPTY)) { boolean connected = awaitBusy(() -> { @@ -56,7 +54,6 @@ public class ShieldTransportClientIT extends ESIntegTestCase { } } - @Test public void testThatTransportClientAuthenticationWithTransportClientRole() throws Exception { Settings settings = Settings.builder() .put("shield.user", TRANSPORT_USER_PW) @@ -78,7 +75,6 @@ public class ShieldTransportClientIT extends ESIntegTestCase { } } - @Test public void testTransportClientWithAdminUser() throws Exception { final boolean useTransportUser = randomBoolean(); Settings settings = Settings.builder() diff --git a/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index dd1b6f857dc..d7e16c99de2 100644 --- a/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -17,18 +17,16 @@ import org.elasticsearch.plugins.Plugin; import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; import java.util.Collection; import java.util.Collections; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; /** * Integration test to test authentication with the custom realm */ public class CustomRealmIT extends ESIntegTestCase { - @Override protected Settings externalClusterClientSettings() { return Settings.builder() @@ -42,7 +40,6 @@ public class CustomRealmIT extends ESIntegTestCase { return Collections.>singleton(ShieldPlugin.class); } - @Test public void testHttpConnectionWithNoAuthentication() throws Exception { HttpResponse response = httpClient().path("/").execute(); assertThat(response.getStatusCode(), is(401)); @@ -50,7 +47,6 @@ public class CustomRealmIT extends ESIntegTestCase { assertThat(value, is("custom-challenge")); } - @Test public void testHttpAuthentication() throws Exception { HttpResponse response = httpClient().path("/") .addHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER) @@ -59,7 +55,6 @@ public class CustomRealmIT extends ESIntegTestCase { assertThat(response.getStatusCode(), is(200)); } - @Test public void testTransportClient() throws Exception { NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get(); NodeInfo[] nodes = nodeInfos.getNodes(); @@ -79,7 +74,6 @@ public class CustomRealmIT extends ESIntegTestCase { } } - @Test public void testTransportClientWrongAuthentication() throws Exception { NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get(); NodeInfo[] nodes = nodeInfos.getNodes(); diff --git a/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java b/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java index 2f8bdf8ab5d..cdba4881cbb 100644 --- a/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java +++ b/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java @@ -11,13 +11,12 @@ import org.elasticsearch.shield.authc.RealmConfig; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; public class CustomRealmTests extends ESTestCase { - - @Test public void testAuthenticate() { Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); CustomRealm realm = new CustomRealm(new RealmConfig("test", Settings.EMPTY, globalSettings)); @@ -28,7 +27,6 @@ public class CustomRealmTests extends ESTestCase { assertThat(user.principal(), equalTo(CustomRealm.KNOWN_USER)); } - @Test public void testAuthenticateBadUser() { Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); CustomRealm realm = new CustomRealm(new RealmConfig("test", Settings.EMPTY, globalSettings)); diff --git a/qa/shield-tribe-node-tests/src/test/java/org/elasticsearch/shield/TribeRestTestCase.java b/qa/shield-tribe-node-tests/src/test/java/org/elasticsearch/shield/TribeRestTestCase.java index 5d2f3a9ce34..7abc9dda591 100644 --- a/qa/shield-tribe-node-tests/src/test/java/org/elasticsearch/shield/TribeRestTestCase.java +++ b/qa/shield-tribe-node-tests/src/test/java/org/elasticsearch/shield/TribeRestTestCase.java @@ -8,6 +8,7 @@ package org.elasticsearch.shield; import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.annotations.TestGroup; import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; + import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.util.LuceneTestCase.SuppressFsync; @@ -16,12 +17,7 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.InetSocketTransportAddress; -import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.node.Node; -import org.elasticsearch.repositories.uri.URLRepository; -import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.rest.ESRestTestCase; @@ -41,7 +37,6 @@ import org.elasticsearch.test.rest.support.FileUtils; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -50,7 +45,12 @@ import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.net.*; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.UnknownHostException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -228,13 +228,13 @@ public abstract class TribeRestTestCase extends ESTestCase { @SuppressForbidden(reason = "proper use of URL, hack around a JDK bug") static FileSystem getFileSystem() throws IOException { // REST suite handling is currently complicated, with lots of filtering and so on - // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents. + // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents. URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation(); boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true); if (codeLocation.getFile().endsWith(".jar") && loadPackaged) { try { // hack around a bug in the zipfilesystem implementation before java 9, - // its checkWritable was incorrect and it won't work without write permissions. + // its checkWritable was incorrect and it won't work without write permissions. // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location. Path tmp = Files.createTempFile(null, ".jar"); try (InputStream in = codeLocation.openStream()) { @@ -349,7 +349,6 @@ public abstract class TribeRestTestCase extends ESTestCase { return messageBuilder.toString(); } - @Test public void test() throws IOException { //let's check that there is something to run, otherwise there might be a problem with the test section if (testCandidate.getTestSection().getExecutableSections().size() == 0) { diff --git a/qa/smoke-test-found-license-with-shield-and-watcher/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java b/qa/smoke-test-found-license-with-shield-and-watcher/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java index 7bf94128f8e..f51044a74ec 100644 --- a/qa/smoke-test-found-license-with-shield-and-watcher/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java +++ b/qa/smoke-test-found-license-with-shield-and-watcher/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java @@ -7,7 +7,6 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import org.elasticsearch.test.rest.RestTestCandidate; -import org.junit.Test; import java.io.IOException; @@ -15,12 +14,10 @@ import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; public class WatcherWithShieldInsufficientRoleIT extends WatcherWithShieldIT { - public WatcherWithShieldInsufficientRoleIT(@Name("yaml") RestTestCandidate testCandidate) { super(testCandidate); } - @Test public void test() throws IOException { try { super.test(); @@ -37,4 +34,3 @@ public class WatcherWithShieldInsufficientRoleIT extends WatcherWithShieldIT { return new String[]{"powerless_user", "changeme"}; } } - diff --git a/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java b/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java index 7bf94128f8e..f51044a74ec 100644 --- a/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java +++ b/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldInsufficientRoleIT.java @@ -7,7 +7,6 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import org.elasticsearch.test.rest.RestTestCandidate; -import org.junit.Test; import java.io.IOException; @@ -15,12 +14,10 @@ import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; public class WatcherWithShieldInsufficientRoleIT extends WatcherWithShieldIT { - public WatcherWithShieldInsufficientRoleIT(@Name("yaml") RestTestCandidate testCandidate) { super(testCandidate); } - @Test public void test() throws IOException { try { super.test(); @@ -37,4 +34,3 @@ public class WatcherWithShieldInsufficientRoleIT extends WatcherWithShieldIT { return new String[]{"powerless_user", "changeme"}; } } - diff --git a/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index fb0f7a8275d..8fb9a545e88 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -27,20 +27,27 @@ import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.BeforeClass; -import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.sameInstance; /** * */ public class ClearRealmsCacheTests extends ShieldIntegTestCase { - private static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); private static String[] usernames; @@ -211,28 +218,23 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { "r1:" + Strings.arrayToCommaDelimitedString(usernames); } - @Test public void testEvictAll() throws Exception { testScenario(Scenario.EVICT_ALL); } - @Test public void testEvictSome() throws Exception { testScenario(Scenario.EVICT_SOME); } - @Test public void testEvictAllHttp() throws Exception { testScenario(Scenario.EVICT_ALL_HTTP); } - @Test public void testEvictSomeHttp() throws Exception { testScenario(Scenario.EVICT_SOME_HTTP); } private void testScenario(Scenario scenario) throws Exception { - Map tokens = new HashMap<>(); for (String user : usernames) { tokens.put(user, new UsernamePasswordToken(user, SecuredStringTests.build("passwd"))); @@ -243,7 +245,6 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { realms.add(nodeRealms.realm("esusers")); } - // we authenticate each user on each of the realms to make sure they're all cached Map> users = new HashMap<>(); for (Realm realm : realms) { diff --git a/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java b/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java index 020c7122cf6..bc4ef9b5392 100644 --- a/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -35,19 +35,23 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.transport.Transport; import org.junit.After; -import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class LicensingTests extends ShieldIntegTestCase { - public static final String ROLES = ShieldSettingsSource.DEFAULT_ROLE + ":\n" + " cluster: all\n" + @@ -112,7 +116,6 @@ public class LicensingTests extends ShieldIntegTestCase { enableLicensing(); } - @Test public void testEnableDisableBehaviour() throws Exception { IndexResponse indexResponse = index("test", "type", jsonBuilder() .startObject() @@ -187,7 +190,6 @@ public class LicensingTests extends ShieldIntegTestCase { assertThat(nodeStats, notNullValue()); } - @Test public void testRestAuthenticationByLicenseType() throws Exception { // the default of the licensing tests is basic assertThat(httpClient().path("/").execute().getStatusCode(), is(200)); @@ -198,7 +200,6 @@ public class LicensingTests extends ShieldIntegTestCase { assertThat(httpClient().path("/").execute().getStatusCode(), is(401)); } - @Test public void testTransportClientAuthenticationByLicenseType() throws Exception { Settings.Builder builder = Settings.builder() .put(internalCluster().transportClient().settings()); diff --git a/shield/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java b/shield/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java index 20a95ed0c04..e9d5f503570 100644 --- a/shield/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.shield.authc.support.SecuredStringTests; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.indicesQuery; @@ -28,7 +27,6 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFa import static org.hamcrest.Matchers.is; public class MultipleIndicesPermissionsTests extends ShieldIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); @Override @@ -64,7 +62,6 @@ public class MultipleIndicesPermissionsTests extends ShieldIntegTestCase { "role_b:user_ab\n"; } - @Test public void testSingleRole() throws Exception { IndexResponse indexResponse = index("test", "type", jsonBuilder() .startObject() @@ -140,16 +137,13 @@ public class MultipleIndicesPermissionsTests extends ShieldIntegTestCase { assertHitCount(searchResponse, 1); } - @Test public void testMultipleRoles() throws Exception { - IndexResponse indexResponse = index("a", "type", jsonBuilder() .startObject() .field("name", "value_a") .endObject()); assertThat(indexResponse.isCreated(), is(true)); - indexResponse = index("b", "type", jsonBuilder() .startObject() .field("name", "value_b") diff --git a/shield/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java b/shield/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java index 5e198974e99..26660d39673 100644 --- a/shield/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.SecuredStringTests; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import java.util.List; @@ -32,7 +31,6 @@ import static org.hamcrest.Matchers.hasSize; * index template actions. */ public class PermissionPrecedenceTests extends ShieldIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("test123".toCharArray()))); @Override @@ -86,9 +84,7 @@ public class PermissionPrecedenceTests extends ShieldIntegTestCase { return new SecuredString("test123".toCharArray()); } - @Test public void testDifferentCombinationsOfIndices() throws Exception { - Client client = internalCluster().transportClient(); // first lets try with "admin"... all should work diff --git a/shield/src/test/java/org/elasticsearch/integration/ScrollIdSigningTests.java b/shield/src/test/java/org/elasticsearch/integration/ScrollIdSigningTests.java index 5bd769bb60a..7bf8546063c 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ScrollIdSigningTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ScrollIdSigningTests.java @@ -13,18 +13,17 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.shield.crypto.CryptoService; import org.elasticsearch.shield.crypto.InternalCryptoService; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import java.util.Locale; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthorizationException; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; public class ScrollIdSigningTests extends ShieldIntegTestCase { - - @Test public void testSearchAndClearScroll() throws Exception { IndexRequestBuilder[] docs = new IndexRequestBuilder[randomIntBetween(20, 100)]; for (int i = 0; i < docs.length; i++) { @@ -54,8 +53,7 @@ public class ScrollIdSigningTests extends ShieldIntegTestCase { } } - @Test - public void testSearchScroll_WithTamperedScrollId() throws Exception { + public void testSearchScrollWithTamperedScrollId() throws Exception { IndexRequestBuilder[] docs = new IndexRequestBuilder[randomIntBetween(20, 100)]; for (int i = 0; i < docs.length; i++) { docs[i] = client().prepareIndex("idx", "type").setSource("field", "value"); @@ -79,8 +77,7 @@ public class ScrollIdSigningTests extends ShieldIntegTestCase { } } - @Test - public void testClearScroll_WithTamperedScrollId() throws Exception { + public void testClearScrollWithTamperedScrollId() throws Exception { IndexRequestBuilder[] docs = new IndexRequestBuilder[randomIntBetween(20, 100)]; for (int i = 0; i < docs.length; i++) { docs[i] = client().prepareIndex("idx", "type").setSource("field", "value"); diff --git a/shield/src/test/java/org/elasticsearch/integration/SearchGetAndSuggestPermissionsTests.java b/shield/src/test/java/org/elasticsearch/integration/SearchGetAndSuggestPermissionsTests.java index bdb21b26c8f..e9429d0f07b 100644 --- a/shield/src/test/java/org/elasticsearch/integration/SearchGetAndSuggestPermissionsTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/SearchGetAndSuggestPermissionsTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.SecuredStringTests; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; @@ -28,7 +27,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class SearchGetAndSuggestPermissionsTests extends ShieldIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); @Override @@ -68,8 +66,7 @@ public class SearchGetAndSuggestPermissionsTests extends ShieldIntegTestCase { /** * testing both "search" and "suggest" privileges can execute the suggest API */ - @Test - public void testSuggestAPI() throws Exception { + public void testSuggestAPI() throws Exception { IndexResponse indexResponse = index("a", "type", jsonBuilder() .startObject() .field("name", "value") @@ -106,7 +103,6 @@ public class SearchGetAndSuggestPermissionsTests extends ShieldIntegTestCase { /** * testing that "search" privilege cannot execute the get API */ - @Test public void testGetAPI() throws Exception { IndexResponse indexResponse = index("a", "type", jsonBuilder() .startObject() @@ -133,7 +129,6 @@ public class SearchGetAndSuggestPermissionsTests extends ShieldIntegTestCase { /** * testing that "get" privilege can execute the mget API, and "search" privilege cannot execute mget */ - @Test public void testMultiGetAPI() throws Exception { IndexResponse indexResponse = index("a", "type", jsonBuilder() .startObject() @@ -167,7 +162,6 @@ public class SearchGetAndSuggestPermissionsTests extends ShieldIntegTestCase { /** * testing that "search" privilege can execute the msearch API */ - @Test public void testMultiSearchAPI() throws Exception { IndexResponse indexResponse = index("a", "type", jsonBuilder() .startObject() diff --git a/shield/src/test/java/org/elasticsearch/integration/SettingsFilterTests.java b/shield/src/test/java/org/elasticsearch/integration/SettingsFilterTests.java index cda16a7af6b..5da941e89c3 100644 --- a/shield/src/test/java/org/elasticsearch/integration/SettingsFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/SettingsFilterTests.java @@ -16,12 +16,12 @@ import org.elasticsearch.node.Node; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.ssl.AbstractSSLService; +import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.After; -import org.junit.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -30,7 +30,6 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import static org.elasticsearch.test.ESIntegTestCase.ClusterScope; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; @@ -38,7 +37,6 @@ import static org.hamcrest.Matchers.is; @ClusterScope(scope = SUITE) public class SettingsFilterTests extends ShieldIntegTestCase { - private CloseableHttpClient httpClient = HttpClients.createDefault(); @After @@ -109,7 +107,6 @@ public class SettingsFilterTests extends ShieldIntegTestCase { return false; } - @Test public void testFiltering() throws Exception { HttpResponse response = executeRequest("GET", "/_nodes", null, Collections.emptyMap()); List list = extractSettings(response.getBody()); diff --git a/shield/src/test/java/org/elasticsearch/integration/ShieldCachePermissionTests.java b/shield/src/test/java/org/elasticsearch/integration/ShieldCachePermissionTests.java index a920a9d16d2..85b636749b7 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ShieldCachePermissionTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ShieldCachePermissionTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Test; import java.util.Collections; @@ -28,7 +27,6 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class ShieldCachePermissionTests extends ShieldIntegTestCase { - static final String READ_ONE_IDX_USER = "read_user"; @Override @@ -75,7 +73,6 @@ public class ShieldCachePermissionTests extends ShieldIntegTestCase { refresh(); } - @Test public void testThatTermsFilterQueryDoesntLeakData() { SearchResponse response = client().prepareSearch("data").setTypes("a").setQuery(QueryBuilders.constantScoreQuery( QueryBuilders.termsLookupQuery("token", new TermsLookup("tokens", "tokens", "1", "tokens")))) @@ -96,7 +93,6 @@ public class ShieldCachePermissionTests extends ShieldIntegTestCase { } } - @Test public void testThatScriptServiceDoesntLeakData() { SearchResponse response = client().prepareSearch("data").setTypes("a") .setTemplate(new Template("testTemplate", ScriptService.ScriptType.INDEXED, MustacheScriptEngineService.NAME, null, Collections.singletonMap("name", "token"))) diff --git a/shield/src/test/java/org/elasticsearch/integration/ShieldClearScrollTests.java b/shield/src/test/java/org/elasticsearch/integration/ShieldClearScrollTests.java index 26734896e08..48628bfcc95 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ShieldClearScrollTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ShieldClearScrollTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.ShieldIntegTestCase; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.List; @@ -28,7 +27,6 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class ShieldClearScrollTests extends ShieldIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); private List scrollIds; @@ -84,7 +82,6 @@ public class ShieldClearScrollTests extends ShieldIntegTestCase { client().prepareClearScroll().addScrollId("_all").get(); } - @Test public void testThatClearingAllScrollIdsWorks() throws Exception { String shieldUser = "allowed_user:change_me"; String basicAuth = basicAuthHeaderValue("allowed_user", new SecuredString("change_me".toCharArray())); @@ -97,7 +94,6 @@ public class ShieldClearScrollTests extends ShieldIntegTestCase { assertThatScrollIdsDoNotExist(scrollIds); } - @Test public void testThatClearingAllScrollIdsRequirePermissions() throws Exception { String shieldUser = "denied_user:change_me"; String basicAuth = basicAuthHeaderValue("denied_user", new SecuredString("change_me".toCharArray())); diff --git a/shield/src/test/java/org/elasticsearch/integration/ldap/GroupMappingTests.java b/shield/src/test/java/org/elasticsearch/integration/ldap/GroupMappingTests.java index c8fe56e9a79..fc879b46db8 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ldap/GroupMappingTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ldap/GroupMappingTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.integration.ldap; import org.elasticsearch.test.junit.annotations.Network; -import org.junit.Test; import java.io.IOException; @@ -16,14 +15,11 @@ import java.io.IOException; */ @Network public class GroupMappingTests extends AbstractAdLdapRealmTestCase { - - @Test public void testAuthcAuthz() throws IOException { String avenger = realmConfig.loginWithCommonName ? "Natasha Romanoff" : "blackwidow"; assertAccessAllowed(avenger, "avengers"); } - @Test public void testGroupMapping() throws IOException { String asgardian = "odin"; String shieldPhilanthropist = realmConfig.loginWithCommonName ? "Bruce Banner" : "hulk"; diff --git a/shield/src/test/java/org/elasticsearch/integration/ldap/MultiGroupMappingTests.java b/shield/src/test/java/org/elasticsearch/integration/ldap/MultiGroupMappingTests.java index 6ca3de93be2..d211e6aa3ab 100644 --- a/shield/src/test/java/org/elasticsearch/integration/ldap/MultiGroupMappingTests.java +++ b/shield/src/test/java/org/elasticsearch/integration/ldap/MultiGroupMappingTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.integration.ldap; import org.elasticsearch.test.junit.annotations.Network; -import org.junit.Test; import java.io.IOException; @@ -15,7 +14,6 @@ import java.io.IOException; */ @Network public class MultiGroupMappingTests extends AbstractAdLdapRealmTestCase { - @Override protected String configRoles() { return super.configRoles() + @@ -39,7 +37,6 @@ public class MultiGroupMappingTests extends AbstractAdLdapRealmTestCase { " - \"cn=Philanthropists,ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com\""; } - @Test public void testGroupMapping() throws IOException { String asgardian = "odin"; String shieldPhilanthropist = realmConfig.loginWithCommonName ? "Bruce Banner" : "hulk"; diff --git a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java index 53535cdc0ef..2cc1c2e190e 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java @@ -27,19 +27,20 @@ import org.elasticsearch.transport.TransportService; import org.hamcrest.Matcher; import org.junit.After; import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import static org.elasticsearch.rest.RestStatus.OK; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; /** * */ public class ShieldPluginEnabledDisabledTests extends ShieldIntegTestCase { - private static boolean enabled; @BeforeClass @@ -84,7 +85,6 @@ public class ShieldPluginEnabledDisabledTests extends ShieldIntegTestCase { return LicensingTests.InternalLicensePlugin.NAME; } - @Test public void testTransportEnabledDisabled() throws Exception { for (TransportService service : internalCluster().getInstances(TransportService.class)) { Matcher matcher = instanceOf(ShieldServerTransportService.class); @@ -102,7 +102,6 @@ public class ShieldPluginEnabledDisabledTests extends ShieldIntegTestCase { } } - @Test public void testShieldInfoStatus() throws IOException { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); OperationMode mode; diff --git a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginSettingsTests.java b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginSettingsTests.java index d21a144cfa5..094179b522a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginSettingsTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginSettingsTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.shield; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; @@ -15,11 +14,9 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.arrayContaining; public class ShieldPluginSettingsTests extends ESTestCase { - private static final String TRIBE_T1_SHIELD_ENABLED = "tribe.t1." + ShieldPlugin.ENABLED_SETTING_NAME; private static final String TRIBE_T2_SHIELD_ENABLED = "tribe.t2." + ShieldPlugin.ENABLED_SETTING_NAME; - @Test public void testShieldIsMandatoryOnTribes() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .put("tribe.t2.cluster.name", "non_existing").build(); @@ -33,7 +30,6 @@ public class ShieldPluginSettingsTests extends ESTestCase { assertThat(additionalSettings.getAsArray("tribe.t2.plugin.mandatory", null), arrayContaining(ShieldPlugin.NAME)); } - @Test public void testAdditionalMandatoryPluginsOnTribes() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .putArray("tribe.t1.plugin.mandatory", "test_plugin").build(); @@ -50,7 +46,6 @@ public class ShieldPluginSettingsTests extends ESTestCase { } } - @Test public void testMandatoryPluginsOnTribesShieldAlreadyMandatory() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .putArray("tribe.t1.plugin.mandatory", "test_plugin", ShieldPlugin.NAME).build(); @@ -67,7 +62,6 @@ public class ShieldPluginSettingsTests extends ESTestCase { assertThat(finalMandatoryPlugins[1], equalTo(ShieldPlugin.NAME)); } - @Test public void testShieldIsEnabledByDefaultOnTribes() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .put("tribe.t2.cluster.name", "non_existing").build(); @@ -80,7 +74,6 @@ public class ShieldPluginSettingsTests extends ESTestCase { assertThat(additionalSettings.getAsBoolean(TRIBE_T2_SHIELD_ENABLED, null), equalTo(true)); } - @Test public void testShieldDisabledOnATribe() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .put(TRIBE_T1_SHIELD_ENABLED, false) @@ -96,7 +89,6 @@ public class ShieldPluginSettingsTests extends ESTestCase { } } - @Test public void testShieldDisabledOnTribesShieldAlreadyMandatory() { Settings settings = Settings.builder().put("tribe.t1.cluster.name", "non_existing") .put(TRIBE_T1_SHIELD_ENABLED, false) diff --git a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java index f32fe65342f..bcc4c04cbf0 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java @@ -15,17 +15,17 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; import java.io.IOException; import static org.elasticsearch.rest.RestStatus.OK; import static org.elasticsearch.rest.RestStatus.UNAUTHORIZED; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; public class ShieldPluginTests extends ShieldIntegTestCase { - @Override public Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -34,7 +34,6 @@ public class ShieldPluginTests extends ShieldIntegTestCase { .build(); } - @Test public void testThatPluginIsLoaded() throws IOException { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { diff --git a/shield/src/test/java/org/elasticsearch/shield/UserTests.java b/shield/src/test/java/org/elasticsearch/shield/UserTests.java index 97c80530e99..df76e9ea66a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/UserTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/UserTests.java @@ -9,15 +9,17 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.common.io.stream.ByteBufferStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.Arrays; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; public class UserTests extends ESTestCase { - - @Test public void testWriteToAndReadFrom() throws Exception { User user = new User.Simple(randomAsciiOfLengthBetween(4, 30), generateRandomStringArray(20, 30, false)); BytesStreamOutput output = new BytesStreamOutput(); @@ -31,7 +33,6 @@ public class UserTests extends ESTestCase { assertThat(readFrom.runAs(), is(nullValue())); } - @Test public void testWriteToAndReadFromWithRunAs() throws Exception { User runAs = new User.Simple(randomAsciiOfLengthBetween(4, 30), randomBoolean() ? generateRandomStringArray(20, 30, false) : null); User user = new User.Simple(randomAsciiOfLengthBetween(4, 30), generateRandomStringArray(20, 30, false), runAs); @@ -50,7 +51,6 @@ public class UserTests extends ESTestCase { assertThat(readFromRunAs.runAs(), is(nullValue())); } - @Test public void testSystemReadAndWrite() throws Exception { BytesStreamOutput output = new BytesStreamOutput(); @@ -63,7 +63,6 @@ public class UserTests extends ESTestCase { assertThat(readFrom.runAs(), is(nullValue())); } - @Test public void testFakeSystemUserSerialization() throws Exception { BytesStreamOutput output = new BytesStreamOutput(); output.writeBoolean(true); @@ -76,7 +75,6 @@ public class UserTests extends ESTestCase { } } - @Test public void testCreateUserRunningAsSystemUser() throws Exception { try { new User.Simple(randomAsciiOfLengthBetween(3, 10), generateRandomStringArray(16, 30, false), User.SYSTEM); diff --git a/shield/src/test/java/org/elasticsearch/shield/VersionCompatibilityTests.java b/shield/src/test/java/org/elasticsearch/shield/VersionCompatibilityTests.java index 4d8a02b1779..505a8ea2ea1 100644 --- a/shield/src/test/java/org/elasticsearch/shield/VersionCompatibilityTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/VersionCompatibilityTests.java @@ -6,9 +6,7 @@ package org.elasticsearch.shield; import org.elasticsearch.Version; -import org.elasticsearch.shield.license.ShieldLicensee; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.hamcrest.CoreMatchers.is; @@ -25,8 +23,6 @@ import static org.hamcrest.CoreMatchers.is; * helps keeping track of this and eventually making changes when needed. */ public class VersionCompatibilityTests extends ESTestCase { - - @Test public void testCompatibility() { /** * see https://github.com/elasticsearch/elasticsearch/issues/9372 {@link ShieldLicensee} diff --git a/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionFilterTests.java index 2c4a8fbd42c..8dc60204161 100644 --- a/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionFilterTests.java @@ -20,20 +20,25 @@ import org.elasticsearch.shield.crypto.CryptoService; import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.util.HashSet; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.*; +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.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * */ public class ShieldActionFilterTests extends ESTestCase { - private AuthenticationService authcService; private AuthorizationService authzService; private CryptoService cryptoService; @@ -53,7 +58,6 @@ public class ShieldActionFilterTests extends ESTestCase { filter = new ShieldActionFilter(Settings.EMPTY, authcService, authzService, cryptoService, auditTrail, shieldLicenseState, new ShieldActionMapper(), new HashSet()); } - @Test public void testApply() throws Exception { ActionRequest request = mock(ActionRequest.class); ActionListener listener = mock(ActionListener.class); @@ -66,8 +70,7 @@ public class ShieldActionFilterTests extends ESTestCase { verify(chain).proceed(eq("_action"), eq(request), isA(ShieldActionFilter.SigningListener.class)); } - @Test - public void testAction_Process_Exception() throws Exception { + public void testActionProcessException() throws Exception { ActionRequest request = mock(ActionRequest.class); ActionListener listener = mock(ActionListener.class); ActionFilterChain chain = mock(ActionFilterChain.class); @@ -80,8 +83,7 @@ public class ShieldActionFilterTests extends ESTestCase { verifyNoMoreInteractions(chain); } - @Test - public void testAction_Signature() throws Exception { + public void testActionSignature() throws Exception { SearchScrollRequest request = new SearchScrollRequest("signed_scroll_id"); ActionListener listener = mock(ActionListener.class); ActionFilterChain chain = mock(ActionFilterChain.class); @@ -95,8 +97,7 @@ public class ShieldActionFilterTests extends ESTestCase { verify(chain).proceed(eq("_action"), eq(request), isA(ShieldActionFilter.SigningListener.class)); } - @Test - public void testAction_SignatureError() throws Exception { + public void testActionSignatureError() throws Exception { SearchScrollRequest request = new SearchScrollRequest("scroll_id"); ActionListener listener = mock(ActionListener.class); ActionFilterChain chain = mock(ActionFilterChain.class); @@ -111,7 +112,6 @@ public class ShieldActionFilterTests extends ESTestCase { verifyNoMoreInteractions(chain); } - @Test public void testApplyUnlicensed() throws Exception { ActionRequest request = mock(ActionRequest.class); ActionListener listener = mock(ActionListener.class); diff --git a/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionMapperTests.java b/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionMapperTests.java index bc0df3b1a33..189a15e5ef1 100644 --- a/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionMapperTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/action/ShieldActionMapperTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.action.search.ClearScrollAction; import org.elasticsearch.action.search.ClearScrollRequest; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.KnownActionsTests; -import org.junit.Test; import java.util.ArrayList; import java.util.Collections; @@ -20,8 +19,6 @@ import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; public class ShieldActionMapperTests extends ESTestCase { - - @Test public void testThatAllOrdinaryActionsRemainTheSame() { List actions = new ArrayList<>(); actions.addAll(KnownActionsTests.loadKnownActions()); @@ -45,7 +42,6 @@ public class ShieldActionMapperTests extends ESTestCase { } } - @Test public void testClearScroll() { ShieldActionMapper shieldActionMapper = new ShieldActionMapper(); ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); @@ -56,7 +52,6 @@ public class ShieldActionMapperTests extends ESTestCase { assertThat(shieldActionMapper.action(ClearScrollAction.NAME, clearScrollRequest), equalTo(ClearScrollAction.NAME)); } - @Test public void testClearScrollAll() { ShieldActionMapper shieldActionMapper = new ShieldActionMapper(); ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); @@ -71,7 +66,6 @@ public class ShieldActionMapperTests extends ESTestCase { assertThat(shieldActionMapper.action(ClearScrollAction.NAME, clearScrollRequest), equalTo(ShieldActionMapper.CLUSTER_PERMISSION_SCROLL_CLEAR_ALL_NAME)); } - @Test public void testIndicesAnalyze() { ShieldActionMapper shieldActionMapper = new ShieldActionMapper(); AnalyzeRequest analyzeRequest; @@ -84,7 +78,6 @@ public class ShieldActionMapperTests extends ESTestCase { assertThat(shieldActionMapper.action(AnalyzeAction.NAME, analyzeRequest), equalTo(AnalyzeAction.NAME)); } - @Test public void testClusterAnalyze() { ShieldActionMapper shieldActionMapper = new ShieldActionMapper(); AnalyzeRequest analyzeRequest = new AnalyzeRequest(null).text("text"); diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailModuleTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailModuleTests.java index c2fa48af77a..9e2e3065323 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailModuleTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailModuleTests.java @@ -16,16 +16,15 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPoolModule; import org.elasticsearch.transport.TransportModule; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class AuditTrailModuleTests extends ESTestCase { - - @Test public void testEnabled() throws Exception { Settings settings = Settings.builder() .put("client.type", "node") @@ -36,7 +35,6 @@ public class AuditTrailModuleTests extends ESTestCase { assertThat(auditTrail, is(AuditTrail.NOOP)); } - @Test public void testDisabledByDefault() throws Exception { Settings settings = Settings.builder() .put("client.type", "node").build(); @@ -45,7 +43,6 @@ public class AuditTrailModuleTests extends ESTestCase { assertThat(auditTrail, is(AuditTrail.NOOP)); } - @Test public void testLogfile() throws Exception { Settings settings = Settings.builder() .put("shield.audit.enabled", true) @@ -65,7 +62,6 @@ public class AuditTrailModuleTests extends ESTestCase { } } - @Test public void testUnknownOutput() throws Exception { Settings settings = Settings.builder() .put("shield.audit.enabled", true) @@ -79,5 +75,4 @@ public class AuditTrailModuleTests extends ESTestCase { // expected } } - } diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailServiceTests.java index 2231184ef70..7c47b575563 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/AuditTrailServiceTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.shield.transport.filter.ShieldIpFilterRule; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportMessage; import org.junit.Before; -import org.junit.Test; import java.net.InetAddress; import java.util.HashSet; @@ -28,7 +27,6 @@ import static org.mockito.Mockito.verify; * */ public class AuditTrailServiceTests extends ESTestCase { - private Set auditTrails; private AuditTrailService service; @@ -49,7 +47,6 @@ public class AuditTrailServiceTests extends ESTestCase { restRequest = mock(RestRequest.class); } - @Test public void testAuthenticationFailed() throws Exception { service.authenticationFailed(token, "_action", message); for (AuditTrail auditTrail : auditTrails) { @@ -57,47 +54,41 @@ public class AuditTrailServiceTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_No_Token() throws Exception { + public void testAuthenticationFailedNoToken() throws Exception { service.authenticationFailed("_action", message); for (AuditTrail auditTrail : auditTrails) { verify(auditTrail).authenticationFailed("_action", message); } } - @Test - public void testAuthenticationFailed_Rest_No_Token() throws Exception { + public void testAuthenticationFailedRestNoToken() throws Exception { service.authenticationFailed(restRequest); for (AuditTrail auditTrail : auditTrails) { verify(auditTrail).authenticationFailed(restRequest); } } - @Test - public void testAuthenticationFailed_Rest() throws Exception { + public void testAuthenticationFailedRest() throws Exception { service.authenticationFailed(token, restRequest); for (AuditTrail auditTrail : auditTrails) { verify(auditTrail).authenticationFailed(token, restRequest); } } - @Test - public void testAuthenticationFailed_Realm() throws Exception { + public void testAuthenticationFailedRealm() throws Exception { service.authenticationFailed("_realm", token, "_action", message); for (AuditTrail auditTrail : auditTrails) { verify(auditTrail).authenticationFailed("_realm", token, "_action", message); } } - @Test - public void testAuthenticationFailed_Rest_Realm() throws Exception { + public void testAuthenticationFailedRestRealm() throws Exception { service.authenticationFailed("_realm", token, restRequest); for (AuditTrail auditTrail : auditTrails) { verify(auditTrail).authenticationFailed("_realm", token, restRequest); } } - @Test public void testAnonymousAccess() throws Exception { service.anonymousAccessDenied("_action", message); for (AuditTrail auditTrail : auditTrails) { @@ -105,7 +96,6 @@ public class AuditTrailServiceTests extends ESTestCase { } } - @Test public void testAccessGranted() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); service.accessGranted(user, "_action", message); @@ -114,7 +104,6 @@ public class AuditTrailServiceTests extends ESTestCase { } } - @Test public void testAccessDenied() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); service.accessDenied(user, "_action", message); @@ -123,7 +112,6 @@ public class AuditTrailServiceTests extends ESTestCase { } } - @Test public void testConnectionGranted() throws Exception { InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = randomBoolean() ? ShieldIpFilterRule.ACCEPT_ALL : IPFilter.DEFAULT_PROFILE_ACCEPT_ALL; @@ -133,7 +121,6 @@ public class AuditTrailServiceTests extends ESTestCase { } } - @Test public void testConnectionDenied() throws Exception { InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = new ShieldIpFilterRule(false, "_all"); diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditLevelTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditLevelTests.java index 83955b5cb09..d43cdc56fc3 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditLevelTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditLevelTests.java @@ -6,16 +6,14 @@ package org.elasticsearch.shield.audit.index; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.EnumSet; import java.util.Locale; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; public class IndexAuditLevelTests extends ESTestCase { - - @Test public void testAllIndexAuditLevel() { EnumSet enumSet = IndexAuditLevel.parse(new String[] { "_all" }); IndexAuditLevel[] levels = IndexAuditLevel.values(); @@ -25,13 +23,11 @@ public class IndexAuditLevelTests extends ESTestCase { } } - @Test public void testExcludeHasPreference() { EnumSet enumSet = IndexAuditLevel.parse(new String[] { "_all" }, new String[] { "_all" }); assertThat(enumSet.size(), is(0)); } - @Test public void testExcludeHasPreferenceSingle() { String excluded = randomFrom(IndexAuditLevel.values()).toString().toLowerCase(Locale.ROOT); EnumSet enumSet = IndexAuditLevel.parse(new String[] { "_all" }, new String[] { excluded }); @@ -39,5 +35,4 @@ public class IndexAuditLevelTests extends ESTestCase { expected.remove(IndexAuditLevel.valueOf(excluded.toUpperCase(Locale.ROOT))); assertThat(enumSet, equalTo(expected)); } - } diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailEnabledTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailEnabledTests.java index e986d48e530..2aa54061d7a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailEnabledTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailEnabledTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ShieldIntegTestCase; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.Collections; import java.util.Set; @@ -25,7 +24,6 @@ import static org.hamcrest.Matchers.is; @ClusterScope(scope = Scope.TEST, randomDynamicTemplates = false) public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase { - IndexNameResolver.Rollover rollover = randomFrom(IndexNameResolver.Rollover.values()); @Override @@ -55,7 +53,6 @@ public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase { // after the test has completed } - @Test public void testAuditTrailIndexAndTemplateExists() throws Exception { awaitIndexTemplateCreation(); @@ -63,7 +60,6 @@ public class IndexAuditTrailEnabledTests extends ShieldIntegTestCase { awaitIndexCreation(); } - @Test public void testAuditTrailTemplateIsRecreatedAfterDelete() throws Exception { // this is already "tested" by the test framework since we wipe the templates before and after, but lets be explicit about the behavior awaitIndexTemplateCreation(); diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailTests.java index ec1262822ec..78cba50580f 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailTests.java @@ -45,7 +45,6 @@ import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; import org.junit.After; -import org.junit.Test; import java.io.IOException; import java.net.InetAddress; @@ -78,7 +77,6 @@ import static org.mockito.Mockito.when; */ @ESIntegTestCase.ClusterScope(scope = SUITE, numDataNodes = 1) public class IndexAuditTrailTests extends ShieldIntegTestCase { - public static final String SECOND_CLUSTER_NODE_PREFIX = "remote_" + SUITE_CLUSTER_NODE_PREFIX; private static final IndexAuditUserHolder user = new IndexAuditUserHolder(); @@ -227,9 +225,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { } } - @Test - public void testAnonymousAccessDenied_Transport() throws Exception { - + public void testAnonymousAccessDeniedTransport() throws Exception { initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.anonymousAccessDenied("_action", message); @@ -253,17 +249,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testAnonymousAccessDenied_Transport_Muted() throws Exception { + public void testAnonymousAccessDeniedTransportMuted() throws Exception { initialize("anonymous_access_denied"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.anonymousAccessDenied("_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test - public void testAnonymousAccessDenied_Rest() throws Exception { - + public void testAnonymousAccessDeniedRest() throws Exception { initialize(); RestRequest request = mockRestRequest(); auditor.anonymousAccessDenied(request); @@ -278,17 +276,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertThat(hit.field("request_body").getValue(), notNullValue()); } - @Test(expected = IndexNotFoundException.class) - public void testAnonymousAccessDenied_Rest_Muted() throws Exception { + public void testAnonymousAccessDeniedRestMuted() throws Exception { initialize("anonymous_access_denied"); RestRequest request = mockRestRequest(); auditor.anonymousAccessDenied(request); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test - public void testAuthenticationFailed_Transport() throws Exception { - + public void testAuthenticationFailedTransport() throws Exception { initialize(); TransportMessage message = randomBoolean() ? new RemoteHostMockMessage() : new LocalHostMockMessage(); auditor.authenticationFailed(new MockToken(), "_action", message); @@ -310,8 +310,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test - public void testAuthenticationFailed_Transport_NoToken() throws Exception { + public void testAuthenticationFailedTransportNoToken() throws Exception { initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.authenticationFailed("_action", message); @@ -337,25 +336,31 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) public void testAuthenticationFailed_Transport_Muted() throws Exception { initialize("authentication_failed"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.authenticationFailed(new MockToken(), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) - public void testAuthenticationFailed_Transport_NoToken_Muted() throws Exception { + public void testAuthenticationFailedTransportNoTokenMuted() throws Exception { initialize("authentication_failed"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.authenticationFailed("_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test - public void testAuthenticationFailed_Rest() throws Exception { - + public void testAuthenticationFailedRest() throws Exception { initialize(); RestRequest request = mockRestRequest(); auditor.authenticationFailed(new MockToken(), request); @@ -371,8 +376,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertThat(hit.field("request_body").getValue(), notNullValue()); } - @Test - public void testAuthenticationFailed_Rest_NoToken() throws Exception { + public void testAuthenticationFailedRestNoToken() throws Exception { initialize(); RestRequest request = mockRestRequest(); auditor.authenticationFailed(request); @@ -388,25 +392,31 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertThat(hit.field("request_body").getValue(), notNullValue()); } - @Test(expected = IndexNotFoundException.class) - public void testAuthenticationFailed_Rest_Muted() throws Exception { + public void testAuthenticationFailedRestMuted() throws Exception { initialize("authentication_failed"); RestRequest request = mockRestRequest(); auditor.authenticationFailed(new MockToken(), request); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) - public void testAuthenticationFailed_Rest_NoToken_Muted() throws Exception { + public void testAuthenticationFailedRestNoTokenMuted() throws Exception { initialize("authentication_failed"); RestRequest request = mockRestRequest(); auditor.authenticationFailed(request); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test - public void testAuthenticationFailed_Transport_Realm() throws Exception { - + public void testAuthenticationFailedTransportRealm() throws Exception { initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.authenticationFailed("_realm", new MockToken(), "_action", message); @@ -433,17 +443,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testAuthenticationFailed_Transport_Realm_Muted() throws Exception { + public void testAuthenticationFailedTransportRealmMuted() throws Exception { initialize("authentication_failed"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.authenticationFailed("_realm", new MockToken(), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test - public void testAuthenticationFailed_Rest_Realm() throws Exception { - + public void testAuthenticationFailedRestRealm() throws Exception { initialize(); RestRequest request = mockRestRequest(); auditor.authenticationFailed("_realm", new MockToken(), request); @@ -459,17 +471,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertThat(hit.field("request_body").getValue(), notNullValue()); } - @Test(expected = IndexNotFoundException.class) - public void testAuthenticationFailed_Rest_Realm_Muted() throws Exception { + public void testAuthenticationFailedRestRealmMuted() throws Exception { initialize("authentication_failed"); RestRequest request = mockRestRequest(); auditor.authenticationFailed("_realm", new MockToken(), request); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testAccessGranted() throws Exception { - initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); final boolean runAs = randomBoolean(); @@ -499,15 +513,18 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testAccessGranted_Muted() throws Exception { + public void testAccessGrantedMuted() throws Exception { initialize("access_granted"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.accessGranted(new User.Simple("_username", new String[]{"r1"}), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testSystemAccessGranted() throws Exception { initialize(new String[] { "system_access_granted" }, null); TransportMessage message = randomBoolean() ? new RemoteHostMockMessage() : new LocalHostMockMessage(); @@ -522,18 +539,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testSystemAccessGranted_Muted() throws Exception { + public void testSystemAccessGrantedMuted() throws Exception { initialize(); TransportMessage message = randomBoolean() ? new RemoteHostMockMessage() : new LocalHostMockMessage(); auditor.accessGranted(User.SYSTEM, "internal:_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); - awaitIndexCreation(resolveIndexName()); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testAccessDenied() throws Exception { - initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); final boolean runAs = randomBoolean(); @@ -563,15 +581,18 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) public void testAccessDenied_Muted() throws Exception { initialize("access_denied"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.accessDenied(new User.Simple("_username", new String[]{"r1"}), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testTamperedRequest() throws Exception { initialize(); TransportRequest message = new RemoteHostMockTransportRequest(); @@ -587,9 +608,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test public void testTamperedRequestWithUser() throws Exception { - initialize(); TransportRequest message = new RemoteHostMockTransportRequest(); final boolean runAs = randomBoolean(); @@ -616,8 +635,7 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testTamperedRequest_Muted() throws Exception { + public void testTamperedRequestMuted() throws Exception { initialize("tampered_request"); TransportRequest message = new RemoteHostMockTransportRequest(); if (randomBoolean()) { @@ -625,12 +643,15 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { } else { auditor.tamperedRequest("_action", message); } - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testConnectionGranted() throws Exception { - initialize(); InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = IPFilter.DEFAULT_PROFILE_ACCEPT_ALL; @@ -644,18 +665,20 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals("default", hit.field("transport_profile").getValue()); } - @Test(expected = IndexNotFoundException.class) - public void testConnectionGranted_Muted() throws Exception { + public void testConnectionGrantedMuted() throws Exception { initialize("connection_granted"); InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = IPFilter.DEFAULT_PROFILE_ACCEPT_ALL; auditor.connectionGranted(inetAddress, "default", rule); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testConnectionDenied() throws Exception { - initialize(); InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = new ShieldIpFilterRule(false, "_all"); @@ -669,16 +692,19 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals("default", hit.field("transport_profile").getValue()); } - @Test(expected = IndexNotFoundException.class) - public void testConnectionDenied_Muted() throws Exception { + public void testConnectionDeniedMuted() throws Exception { initialize("connection_denied"); InetAddress inetAddress = InetAddress.getLoopbackAddress(); ShieldIpFilterRule rule = new ShieldIpFilterRule(false, "_all"); auditor.connectionDenied(inetAddress, "default", rule); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testRunAsGranted() throws Exception { initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); @@ -695,15 +721,18 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testRunAsGranted_Muted() throws Exception { + public void testRunAsGrantedMuted() throws Exception { initialize("run_as_granted"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.runAsGranted(new User.Simple("_username", new String[]{"r1"}, new User.Simple("running as", new String[]{"r2"})), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testRunAsDenied() throws Exception { initialize(); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); @@ -720,12 +749,16 @@ public class IndexAuditTrailTests extends ShieldIntegTestCase { assertEquals(hit.field("request").getValue(), message.getClass().getSimpleName()); } - @Test(expected = IndexNotFoundException.class) - public void testRunAsDenied_Muted() throws Exception { + public void testRunAsDeniedMuted() throws Exception { initialize("run_as_denied"); TransportMessage message = randomFrom(new RemoteHostMockMessage(), new LocalHostMockMessage(), new MockIndicesTransportMessage()); auditor.runAsDenied(new User.Simple("_username", new String[]{"r1"}, new User.Simple("running as", new String[]{"r2"})), "_action", message); - getClient().prepareExists(resolveIndexName()).execute().actionGet(); + try { + getClient().prepareExists(resolveIndexName()).execute().actionGet(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } private void assertAuditMessage(SearchHit hit, String layer, String type) { diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailUpdateMappingTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailUpdateMappingTests.java index f23d35f74d1..8088b2fc26b 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailUpdateMappingTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/index/IndexAuditTrailUpdateMappingTests.java @@ -14,17 +14,19 @@ import org.elasticsearch.common.transport.DummyTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.env.Environment; import org.elasticsearch.shield.authc.AuthenticationService; -import org.elasticsearch.test.*; +import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.Transport; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.Locale; -import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.*; +import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.DAILY; +import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.HOURLY; +import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.MONTHLY; +import static org.elasticsearch.shield.audit.index.IndexNameResolver.Rollover.WEEKLY; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; @@ -34,7 +36,6 @@ import static org.mockito.Mockito.when; * This test checks to make sure that the index audit trail actually updates the mappings on startups */ public class IndexAuditTrailUpdateMappingTests extends ShieldIntegTestCase { - private ThreadPool threadPool; @Before @@ -42,7 +43,6 @@ public class IndexAuditTrailUpdateMappingTests extends ShieldIntegTestCase { threadPool = new ThreadPool("index audit trail update mapping tests"); } - @Test public void testMappingIsUpdated() throws Exception { // Setup IndexNameResolver.Rollover rollover = randomFrom(HOURLY, DAILY, WEEKLY, MONTHLY); diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/index/RemoteIndexAuditTrailStartingTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/index/RemoteIndexAuditTrailStartingTests.java index 299fad90354..5ed09a1259d 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/index/RemoteIndexAuditTrailStartingTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/index/RemoteIndexAuditTrailStartingTests.java @@ -16,10 +16,13 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import static org.elasticsearch.test.InternalTestCluster.clusterName; @@ -132,7 +135,6 @@ public class RemoteIndexAuditTrailStartingTests extends ShieldIntegTestCase { } } - @Test public void testThatRemoteAuditInstancesAreStarted() throws Exception { Iterable auditTrails = remoteCluster.getInstances(IndexAuditTrail.class); for (final IndexAuditTrail auditTrail : auditTrails) { diff --git a/shield/src/test/java/org/elasticsearch/shield/audit/logfile/LoggingAuditTrailTests.java b/shield/src/test/java/org/elasticsearch/shield/audit/logfile/LoggingAuditTrailTests.java index f425ef5cd37..8ea3f1af7dc 100644 --- a/shield/src/test/java/org/elasticsearch/shield/audit/logfile/LoggingAuditTrailTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/audit/logfile/LoggingAuditTrailTests.java @@ -11,9 +11,14 @@ import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.*; +import org.elasticsearch.common.transport.BoundTransportAddress; +import org.elasticsearch.common.transport.DummyTransportAddress; +import org.elasticsearch.common.transport.InetSocketTransportAddress; +import org.elasticsearch.common.transport.LocalTransportAddress; +import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.shield.User; +import org.elasticsearch.shield.audit.logfile.CapturingLogger.Level; import org.elasticsearch.shield.authc.AuthenticationToken; import org.elasticsearch.shield.rest.RemoteHostHeader; import org.elasticsearch.shield.transport.filter.IPFilter; @@ -22,7 +27,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportMessage; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.net.InetAddress; @@ -30,7 +34,6 @@ import java.net.InetSocketAddress; import java.util.List; import java.util.Locale; -import static org.elasticsearch.shield.audit.logfile.CapturingLogger.Level; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; @@ -40,9 +43,7 @@ import static org.mockito.Mockito.when; * */ public class LoggingAuditTrailTests extends ESTestCase { - private static enum RestContent { - VALID() { @Override protected boolean hasContent() { @@ -113,8 +114,7 @@ public class LoggingAuditTrailTests extends ESTestCase { prefix = LoggingAuditTrail.resolvePrefix(settings, transport); } - @Test - public void testAnonymousAccessDenied_Transport() throws Exception { + public void testAnonymousAccessDeniedTransport() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); LoggingAuditTrail auditTrail = new LoggingAuditTrail(settings, transport, logger); @@ -144,8 +144,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAnonymousAccessDenied_Rest() throws Exception { + public void testAnonymousAccessDeniedRest() throws Exception { RestRequest request = mock(RestRequest.class); InetAddress address = forge("_hostname", randomBoolean() ? "127.0.0.1" : "::1"); when(request.getRemoteAddress()).thenReturn(new InetSocketAddress(address, 9200)); @@ -171,7 +170,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testAuthenticationFailed() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -200,8 +198,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_NoToken() throws Exception { + public void testAuthenticationFailedNoToken() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); LoggingAuditTrail auditTrail = new LoggingAuditTrail(settings, transport, logger); @@ -229,8 +226,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_Rest() throws Exception { + public void testAuthenticationFailedRest() throws Exception { for (Level level : Level.values()) { RestRequest request = mock(RestRequest.class); InetAddress address = forge("_hostname", randomBoolean() ? "127.0.0.1" : "::1"); @@ -253,8 +249,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_Rest_NoToken() throws Exception { + public void testAuthenticationFailedRestNoToken() throws Exception { for (Level level : Level.values()) { RestRequest request = mock(RestRequest.class); InetAddress address = forge("_hostname", randomBoolean() ? "127.0.0.1" : "::1"); @@ -277,8 +272,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_Realm() throws Exception { + public void testAuthenticationFailedRealm() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); LoggingAuditTrail auditTrail = new LoggingAuditTrail(settings, transport, logger); @@ -302,8 +296,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAuthenticationFailed_Realm_Rest() throws Exception { + public void testAuthenticationFailedRealmRest() throws Exception { for (Level level : Level.values()) { RestRequest request = mock(RestRequest.class); InetAddress address = forge("_hostname", randomBoolean() ? "127.0.0.1" : "::1"); @@ -326,7 +319,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testAccessGranted() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -365,8 +357,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAccessGranted_InternalSystemAction() throws Exception { + public void testAccessGrantedInternalSystemAction() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); LoggingAuditTrail auditTrail = new LoggingAuditTrail(settings, transport, logger); @@ -390,8 +381,7 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test - public void testAccessGranted_InternalSystemAction_NonSystemUser() throws Exception { + public void testAccessGrantedInternalSystemActionNonSystemUser() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); LoggingAuditTrail auditTrail = new LoggingAuditTrail(settings, transport, logger); @@ -429,7 +419,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testAccessDenied() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -466,7 +455,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testTamperedRequest() throws Exception { String action = "_action"; TransportMessage message = randomBoolean() ? new MockMessage() : new MockIndicesRequest(); @@ -496,7 +484,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testTamperedRequestWithUser() throws Exception { String action = "_action"; TransportMessage message = randomBoolean() ? new MockMessage() : new MockIndicesRequest(); @@ -534,7 +521,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testConnectionDenied() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -555,7 +541,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testConnectionGranted() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -578,7 +563,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testRunAsGranted() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -602,7 +586,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testRunAsDenied() throws Exception { for (Level level : Level.values()) { CapturingLogger logger = new CapturingLogger(level); @@ -626,7 +609,6 @@ public class LoggingAuditTrailTests extends ESTestCase { } } - @Test public void testOriginAttributes() throws Exception { MockMessage message = new MockMessage(); String text = LoggingAuditTrail.originAttributes(message, transport);; diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserHolderTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserHolderTests.java index 85d029f54a0..c744670c241 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserHolderTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserHolderTests.java @@ -10,15 +10,16 @@ import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.User; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.nio.ByteBuffer; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; public class AnonymousUserHolderTests extends ESTestCase { - - @Test public void testResolveAnonymousUser() throws Exception { Settings settings = Settings.builder() .put("shield.authc.anonymous.username", "anonym1") @@ -38,7 +39,6 @@ public class AnonymousUserHolderTests extends ESTestCase { assertThat(user.roles(), arrayContainingInAnyOrder("r1", "r2", "r3")); } - @Test public void testResolveAnonymousUser_NoSettings() throws Exception { Settings settings = randomBoolean() ? Settings.EMPTY : @@ -47,7 +47,6 @@ public class AnonymousUserHolderTests extends ESTestCase { assertThat(user, nullValue()); } - @Test public void testWhenAnonymousDisabled() { AnonymousService anonymousService = new AnonymousService(Settings.EMPTY); assertThat(anonymousService.enabled(), is(false)); @@ -56,7 +55,6 @@ public class AnonymousUserHolderTests extends ESTestCase { assertThat(anonymousService.authorizationExceptionsEnabled(), is(true)); } - @Test public void testWhenAnonymousEnabled() throws Exception { Settings settings = Settings.builder() .putArray("shield.authc.anonymous.roles", "r1", "r2", "r3") @@ -74,7 +72,6 @@ public class AnonymousUserHolderTests extends ESTestCase { assertThat(anonymousService.isAnonymous(anonymousSerialized), is(true)); } - @Test public void testDisablingAuthorizationExceptions() { Settings settings = Settings.builder() .putArray("shield.authc.anonymous.roles", "r1", "r2", "r3") diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserTests.java index 9d5aca55aff..906db24abb0 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/AnonymousUserTests.java @@ -16,16 +16,18 @@ import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.node.Node; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Locale; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; public class AnonymousUserTests extends ShieldIntegTestCase { - private boolean authorizationExceptionsEnabled = randomBoolean(); @Override @@ -51,7 +53,6 @@ public class AnonymousUserTests extends ShieldIntegTestCase { " '*': READ"; } - @Test public void testAnonymousViaHttp() throws Exception { try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(new HttpGet(getNodeUrl() + "_nodes"))) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/AuthenticationModuleTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/AuthenticationModuleTests.java index 444dc7a23f4..40eea778378 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/AuthenticationModuleTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/AuthenticationModuleTests.java @@ -23,16 +23,15 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPoolModule; import org.elasticsearch.transport.TransportMessage; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.notNullValue; /** * Unit tests for the AuthenticationModule */ public class AuthenticationModuleTests extends ESTestCase { - - @Test public void testAddingReservedRealmType() { Settings settings = Settings.EMPTY; AuthenticationModule module = new AuthenticationModule(settings); @@ -45,7 +44,6 @@ public class AuthenticationModuleTests extends ESTestCase { } } - @Test public void testAddingNullOrEmptyType() { Settings settings = Settings.EMPTY; AuthenticationModule module = new AuthenticationModule(settings); @@ -58,7 +56,6 @@ public class AuthenticationModuleTests extends ESTestCase { } } - @Test public void testAddingNullFactory() { Settings settings = Settings.EMPTY; AuthenticationModule module = new AuthenticationModule(settings); @@ -70,7 +67,6 @@ public class AuthenticationModuleTests extends ESTestCase { } } - @Test public void testRegisteringCustomRealm() { Settings settings = Settings.builder() .put("name", "foo") @@ -92,7 +88,6 @@ public class AuthenticationModuleTests extends ESTestCase { } } - @Test public void testDefaultFailureHandler() { Settings settings = Settings.builder() .put("name", "foo") @@ -120,7 +115,6 @@ public class AuthenticationModuleTests extends ESTestCase { } } - @Test public void testSettingFailureHandler() { Settings settings = Settings.builder() .put("name", "foo") @@ -147,7 +141,6 @@ public class AuthenticationModuleTests extends ESTestCase { // this class must be public for injection... public static class NoOpFailureHandler implements AuthenticationFailureHandler { - @Override public ElasticsearchSecurityException unsuccessfulAuthentication(RestRequest request, AuthenticationToken token) { return null; diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/InternalAuthenticationServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/InternalAuthenticationServiceTests.java index 0edcc667203..74309e566a9 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/InternalAuthenticationServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/InternalAuthenticationServiceTests.java @@ -24,7 +24,6 @@ import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.transport.TransportMessage; import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.Arrays; @@ -32,8 +31,23 @@ import java.util.Collections; import static org.elasticsearch.shield.support.Exceptions.authenticationError; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** @@ -84,8 +98,8 @@ public class InternalAuthenticationServiceTests extends ESTestCase { service = new InternalAuthenticationService(Settings.EMPTY, realms, auditTrail, cryptoService, anonymousService, new DefaultAuthenticationFailureHandler()); } - @Test @SuppressWarnings("unchecked") - public void testToken_FirstMissing_SecondFound() throws Exception { + @SuppressWarnings("unchecked") + public void testTokenFirstMissingSecondFound() throws Exception { when(firstRealm.token(message)).thenReturn(null); when(secondRealm.token(message)).thenReturn(token); @@ -95,16 +109,14 @@ public class InternalAuthenticationServiceTests extends ESTestCase { verifyZeroInteractions(auditTrail); } - @Test - public void testToken_Missing() throws Exception { + public void testTokenMissing() throws Exception { AuthenticationToken token = service.token("_action", message); assertThat(token, nullValue()); verifyNoMoreInteractions(auditTrail); assertThat(message.getContext().get(InternalAuthenticationService.TOKEN_KEY), nullValue()); } - @Test @SuppressWarnings("unchecked") - public void testToken_Cached() throws Exception { + public void testTokenCached() throws Exception { message.putInContext(InternalAuthenticationService.TOKEN_KEY, token); AuthenticationToken result = service.token("_action", message); assertThat(result, notNullValue()); @@ -116,8 +128,8 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getContext().get(InternalAuthenticationService.TOKEN_KEY), is((Object) token)); } - @Test @SuppressWarnings("unchecked") - public void testAuthenticate_BothSupport_SecondSucceeds() throws Exception { + @SuppressWarnings("unchecked") + public void testAuthenticateBothSupportSecondSucceeds() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); when(firstRealm.supports(token)).thenReturn(true); when(firstRealm.authenticate(token)).thenReturn(null); // first fails @@ -138,8 +150,8 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_encoded_user")); } - @Test @SuppressWarnings("unchecked") - public void testAuthenticate_FirstNotSupporting_SecondSucceeds() throws Exception { + @SuppressWarnings("unchecked") + public void testAuthenticateFirstNotSupportingSecondSucceeds() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); when(firstRealm.supports(token)).thenReturn(false); when(secondRealm.supports(token)).thenReturn(true); @@ -160,8 +172,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_encoded_user")); } - @Test @SuppressWarnings("unchecked") - public void testAuthenticate_Cached() throws Exception { + public void testAuthenticateCached() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); message.putInContext(InternalAuthenticationService.USER_KEY, user); User result = service.authenticate("_action", message, null); @@ -175,8 +186,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getContext().get(InternalAuthenticationService.USER_KEY), is((Object) user)); } - @Test - public void testAuthenticate_nonExistentRestRequestUserThrowsAuthenticationException() throws Exception { + public void testAuthenticateNonExistentRestRequestUserThrowsAuthenticationException() throws Exception { when(firstRealm.token(restRequest)).thenReturn(new UsernamePasswordToken("idonotexist", new SecuredString("passwd".toCharArray()))); try { service.authenticate(restRequest); @@ -186,8 +196,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testToken_Rest_Exists() throws Exception { + public void testTokenRestExists() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); when(firstRealm.token(restRequest)).thenReturn(null); when(secondRealm.token(restRequest)).thenReturn(token); @@ -196,15 +205,13 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(restRequest.getFromContext(InternalAuthenticationService.TOKEN_KEY), equalTo((Object) token)); } - @Test - public void testToken_Rest_Missing() throws Exception { + public void testTokenRestMissing() throws Exception { when(firstRealm.token(restRequest)).thenReturn(null); when(secondRealm.token(restRequest)).thenReturn(null); AuthenticationToken token = service.token(restRequest); assertThat(token, nullValue()); } - @Test public void testEncodeDecodeUser() throws Exception { User user = new User.Simple("username", new String[] { "r1", "r2", "r3" }); String text = InternalAuthenticationService.encodeUser(user, null); @@ -216,7 +223,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(User.SYSTEM, sameInstance(user2)); } - @Test public void testUserHeader() throws Exception { User user = new User.Simple("_username", new String[] { "r1" }); when(firstRealm.token(message)).thenReturn(token); @@ -233,8 +239,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(userStr, equalTo("_signed_user")); } - @Test - public void testAuthenticate_Transport_Anonymous() throws Exception { + public void testAuthenticateTransportAnonymous() throws Exception { when(firstRealm.token(message)).thenReturn(null); when(secondRealm.token(message)).thenReturn(null); try { @@ -247,8 +252,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { verify(auditTrail).anonymousAccessDenied("_action", message); } - @Test - public void testAuthenticate_Rest_Anonymous() throws Exception { + public void testAuthenticateRestAnonymous() throws Exception { when(firstRealm.token(restRequest)).thenReturn(null); when(secondRealm.token(restRequest)).thenReturn(null); try { @@ -261,8 +265,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { verify(auditTrail).anonymousAccessDenied(restRequest); } - @Test - public void testAuthenticate_Transport_Fallback() throws Exception { + public void testAuthenticateTransportFallback() throws Exception { when(firstRealm.token(message)).thenReturn(null); when(secondRealm.token(message)).thenReturn(null); User.Simple user1 = new User.Simple("username", new String[] { "r1", "r2" }); @@ -273,8 +276,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_signed_user")); } - @Test - public void testAuthenticate_Transport_Success_NoFallback() throws Exception { + public void testAuthenticateTransportSuccessNoFallback() throws Exception { User.Simple user1 = new User.Simple("username", new String[] { "r1", "r2" }); when(firstRealm.token(message)).thenReturn(token); when(firstRealm.supports(token)).thenReturn(true); @@ -286,8 +288,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_signed_user")); } - @Test - public void testAuthenticate_Transport_Success_WithFallback() throws Exception { + public void testAuthenticateTransportSuccessWithFallback() throws Exception { User.Simple user1 = new User.Simple("username", new String[] { "r1", "r2" }); when(firstRealm.token(message)).thenReturn(token); when(firstRealm.supports(token)).thenReturn(true); @@ -299,8 +300,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_signed_user")); } - @Test - public void testAuthenticate_Rest_Success() throws Exception { + public void testAuthenticateRestSuccess() throws Exception { User.Simple user1 = new User.Simple("username", new String[] { "r1", "r2" }); when(firstRealm.token(restRequest)).thenReturn(token); when(firstRealm.supports(token)).thenReturn(true); @@ -310,8 +310,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(restRequest.getFromContext(InternalAuthenticationService.USER_KEY), sameInstance((Object) user2)); } - @Test - public void testAutheticate_Transport_ContextAndHeader() throws Exception { + public void testAutheticateTransportContextAndHeader() throws Exception { User user1 = new User.Simple("username", new String[] { "r1", "r2" }); when(firstRealm.token(message)).thenReturn(token); when(firstRealm.supports(token)).thenReturn(true); @@ -345,8 +344,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { verifyZeroInteractions(firstRealm); } - @Test - public void testAutheticate_Transport_ContextAndHeader_NoSigning() throws Exception { + public void testAutheticateTransportContextAndHeaderNoSigning() throws Exception { Settings settings = Settings.builder().put(InternalAuthenticationService.SETTING_SIGN_USER_HEADER, false).build(); service = new InternalAuthenticationService(settings, realms, auditTrail, cryptoService, anonymousService, new DefaultAuthenticationFailureHandler()); @@ -383,7 +381,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { verifyZeroInteractions(cryptoService); } - @Test public void testAuthenticateTamperedUser() throws Exception { InternalMessage message = new InternalMessage(); message.putHeader(InternalAuthenticationService.USER_KEY, "_signed_user"); @@ -398,8 +395,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testAttachIfMissing_Missing() throws Exception { + public void testAttachIfMissingMissing() throws Exception { User user = new User.Simple("username", new String[] { "r1", "r2" }); assertThat(message.getFromContext(InternalAuthenticationService.USER_KEY), nullValue()); assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), nullValue()); @@ -418,8 +414,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_signed_user")); } - @Test - public void testAttachIfMissing_Exists() throws Exception { + public void testAttachIfMissingExists() throws Exception { User user = new User.Simple("username", new String[] { "r1", "r2" }); message.putInContext(InternalAuthenticationService.USER_KEY, user); message.putHeader(InternalAuthenticationService.USER_KEY, "_signed_user"); @@ -428,8 +423,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getHeader(InternalAuthenticationService.USER_KEY), equalTo((Object) "_signed_user")); } - @Test - public void testAnonymousUser_Rest() throws Exception { + public void testAnonymousUserRest() throws Exception { String username = randomBoolean() ? AnonymousService.ANONYMOUS_USERNAME : "user1"; Settings.Builder builder = Settings.builder() .putArray("shield.authc.anonymous.roles", "r1", "r2", "r3"); @@ -450,8 +444,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(user.roles(), arrayContainingInAnyOrder("r1", "r2", "r3")); } - @Test - public void testAnonymousUser_Transport_NoDefaultUser() throws Exception { + public void testAnonymousUserTransportNoDefaultUser() throws Exception { Settings settings = Settings.builder() .putArray("shield.authc.anonymous.roles", "r1", "r2", "r3") .build(); @@ -465,8 +458,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(user.roles(), arrayContainingInAnyOrder("r1", "r2", "r3")); } - @Test - public void testAnonymousUser_Transport_WithDefaultUser() throws Exception { + public void testAnonymousUserTransportWithDefaultUser() throws Exception { Settings settings = Settings.builder() .putArray("shield.authc.anonymous.roles", "r1", "r2", "r3") .build(); @@ -479,7 +471,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(user, sameInstance(User.SYSTEM)); } - @Test public void testRealmTokenThrowingException() throws Exception { when(firstRealm.token(message)).thenThrow(authenticationError("realm doesn't like tokens")); try { @@ -491,8 +482,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testRealmTokenThrowingException_Rest() throws Exception { + public void testRealmTokenThrowingExceptionRest() throws Exception { when(firstRealm.token(restRequest)).thenThrow(authenticationError("realm doesn't like tokens")); try { service.authenticate(restRequest); @@ -503,7 +493,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test public void testRealmSupportsMethodThrowingException() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); when(secondRealm.token(message)).thenReturn(token); @@ -517,8 +506,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testRealmSupportsMethodThrowingException_Rest() throws Exception { + public void testRealmSupportsMethodThrowingExceptionRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); when(secondRealm.token(restRequest)).thenReturn(token); when(secondRealm.supports(token)).thenThrow(authenticationError("realm doesn't like supports")); @@ -531,7 +519,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test public void testRealmAuthenticateThrowingException() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); when(secondRealm.token(message)).thenReturn(token); @@ -546,8 +533,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testRealmAuthenticateThrowingException_Rest() throws Exception { + public void testRealmAuthenticateThrowingExceptionRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); when(secondRealm.token(restRequest)).thenReturn(token); when(secondRealm.supports(token)).thenReturn(true); @@ -561,7 +547,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test public void testRealmLookupThrowingException() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); message.putHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"); @@ -580,8 +565,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test - public void testRealmLookupThrowingException_Rest() throws Exception { + public void testRealmLookupThrowingExceptionRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); restRequest = new FakeRestRequest(Collections.singletonMap(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"), Collections.emptyMap()); when(secondRealm.token(restRequest)).thenReturn(token); @@ -599,7 +583,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test public void testRunAsLookupSameRealm() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); message.putHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"); @@ -620,8 +603,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getContext().get(InternalAuthenticationService.USER_KEY), sameInstance((Object) authenticated)); } - @Test - public void testRunAsLookupSameRealm_Rest() throws Exception { + public void testRunAsLookupSameRealmRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); restRequest = new FakeRestRequest(Collections.singletonMap(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"), Collections.emptyMap()); when(secondRealm.token(restRequest)).thenReturn(token); @@ -641,7 +623,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(restRequest.getContext().get(InternalAuthenticationService.USER_KEY), sameInstance((Object) authenticated)); } - @Test public void testRunAsLookupDifferentRealm() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); message.putHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"); @@ -663,8 +644,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(message.getContext().get(InternalAuthenticationService.USER_KEY), sameInstance((Object) authenticated)); } - @Test - public void testRunAsLookupDifferentRealm_Rest() throws Exception { + public void testRunAsLookupDifferentRealmRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); restRequest = new FakeRestRequest(Collections.singletonMap(InternalAuthenticationService.RUN_AS_USER_HEADER, "run_as"), Collections.emptyMap()); when(secondRealm.token(restRequest)).thenReturn(token); @@ -684,8 +664,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase { assertThat(restRequest.getContext().get(InternalAuthenticationService.USER_KEY), sameInstance((Object) authenticated)); } - @Test - public void testRunAsWithEmptyRunAsUsername_Rest() throws Exception { + public void testRunAsWithEmptyRunAsUsernameRest() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); restRequest = new FakeRestRequest(Collections.singletonMap(InternalAuthenticationService.RUN_AS_USER_HEADER, ""), Collections.emptyMap()); when(secondRealm.token(restRequest)).thenReturn(token); @@ -702,7 +681,6 @@ public class InternalAuthenticationServiceTests extends ESTestCase { } } - @Test public void testRunAsWithEmptyRunAsUsername() throws Exception { AuthenticationToken token = mock(AuthenticationToken.class); message.putHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ""); @@ -722,5 +700,4 @@ public class InternalAuthenticationServiceTests extends ESTestCase { private static class InternalMessage extends TransportMessage { } - } diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/RealmsTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/RealmsTests.java index f7514d3589e..31c205ff4d5 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/RealmsTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/RealmsTests.java @@ -16,11 +16,19 @@ import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportMessage; import org.junit.Before; -import org.junit.Test; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,7 +36,6 @@ import static org.mockito.Mockito.when; * */ public class RealmsTests extends ESTestCase { - private Map factories; private ShieldSettingsFilter settingsFilter; private ShieldLicenseState shieldLicenseState; @@ -46,7 +53,6 @@ public class RealmsTests extends ESTestCase { when(shieldLicenseState.customRealmsEnabled()).thenReturn(true); } - @Test public void testWithSettings() throws Exception { Settings.Builder builder = Settings.builder() .put("path.home", createTempDir()); @@ -75,8 +81,7 @@ public class RealmsTests extends ESTestCase { } } - @Test(expected = IllegalArgumentException.class) - public void testWithSettings_WithMultipleInternalRealmsOfSameType() throws Exception { + public void testWithSettingsWithMultipleInternalRealmsOfSameType() throws Exception { Settings settings = Settings.builder() .put("shield.authc.realms.realm_1.type", ESUsersRealm.TYPE) .put("shield.authc.realms.realm_1.order", 0) @@ -85,10 +90,14 @@ public class RealmsTests extends ESTestCase { .put("path.home", createTempDir()) .build(); Environment env = new Environment(settings); - new Realms(settings, env, factories, settingsFilter, shieldLicenseState).start(); + try { + new Realms(settings, env, factories, settingsFilter, shieldLicenseState).start(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("multiple [esusers] realms are configured")); + } } - @Test public void testWithEmptySettings() throws Exception { Realms realms = new Realms(Settings.EMPTY, new Environment(Settings.builder().put("path.home", createTempDir()).build()), factories, settingsFilter, shieldLicenseState); @@ -102,7 +111,6 @@ public class RealmsTests extends ESTestCase { assertThat(iter.hasNext(), is(false)); } - @Test public void testUnlicensedWithOnlyCustomRealms() throws Exception { Settings.Builder builder = Settings.builder() .put("path.home", createTempDir()); @@ -140,7 +148,6 @@ public class RealmsTests extends ESTestCase { assertThat(i, is(1)); } - @Test public void testUnlicensedWithInternalRealms() throws Exception { factories.put(LdapRealm.TYPE, new DummyRealm.Factory(LdapRealm.TYPE, false)); assertThat(factories.get("type_0"), notNullValue()); @@ -172,7 +179,6 @@ public class RealmsTests extends ESTestCase { assertThat(i, is(1)); } - @Test public void testDisabledRealmsAreNotAdded() throws Exception { Settings.Builder builder = Settings.builder() .put("path.home", createTempDir()); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java index 2cad0946887..df3294aee2c 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java @@ -20,15 +20,14 @@ import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; /** * */ public class RunAsIntegTests extends ShieldIntegTestCase { - static final String RUN_AS_USER = "run_as_user"; static final String TRANSPORT_CLIENT_USER = "transport_user"; static final String ROLES = @@ -69,7 +68,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { + "transport_client:" + TRANSPORT_CLIENT_USER; } - @Test public void testUserImpersonation() throws Exception { try (TransportClient client = getTransportClient(Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) { //ensure the client can connect @@ -102,7 +100,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } } - @Test public void testUserImpersonationUsingHttp() throws Exception { // use the transport client user and try to run as HttpResponse response = httpClient().method("GET") @@ -128,7 +125,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { assertThat(response.getStatusCode(), is(200)); } - @Test public void testEmptyUserImpersonationHeader() throws Exception { try (TransportClient client = getTransportClient(Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) { //ensure the client can connect @@ -147,7 +143,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } } - @Test public void testEmptyHeaderUsingHttp() throws Exception { HttpResponse response = httpClient().method("GET") .path("/_nodes") @@ -157,7 +152,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { assertThat(response.getStatusCode(), is(401)); } - @Test public void testNonExistentRunAsUser() throws Exception { try (TransportClient client = getTransportClient(Settings.builder().put("shield.user", TRANSPORT_CLIENT_USER + ":" + ShieldSettingsSource.DEFAULT_PASSWORD).build())) { //ensure the client can connect @@ -176,7 +170,6 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } } - @Test public void testNonExistentRunAsUserUsingHttp() throws Exception { HttpResponse response = httpClient().method("GET") .path("/_nodes") diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryGroupsResolverTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryGroupsResolverTests.java index ae3228fb16c..118b212f8df 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryGroupsResolverTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryGroupsResolverTests.java @@ -9,6 +9,7 @@ import com.unboundid.ldap.sdk.Filter; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.ldap.sdk.LDAPURL; + import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; @@ -20,20 +21,22 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.util.List; import java.util.regex.Pattern; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; @Network public class ActiveDirectoryGroupsResolverTests extends ESTestCase { - public static final String BRUCE_BANNER_DN = "cn=Bruce Banner,CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com"; private LDAPConnection ldapConnection; + @Override @Before public void setUp() throws Exception { super.setUp(); @@ -55,13 +58,13 @@ public class ActiveDirectoryGroupsResolverTests extends ESTestCase { ldapConnection = new LDAPConnection(clientSSLService.sslSocketFactory(), options, ldapurl.getHost(), ldapurl.getPort(), BRUCE_BANNER_DN, ActiveDirectorySessionFactoryTests.PASSWORD); } + @Override @After public void tearDown() throws Exception { super.tearDown(); ldapConnection.close(); } - @Test public void testResolveSubTree() throws Exception { Settings settings = Settings.builder() .put("scope", LdapSearchScope.SUB_TREE) @@ -78,7 +81,6 @@ public class ActiveDirectoryGroupsResolverTests extends ESTestCase { containsString("Supers"))); } - @Test public void testResolveOneLevel() throws Exception { Settings settings = Settings.builder() .put("scope", LdapSearchScope.ONE_LEVEL) @@ -89,7 +91,6 @@ public class ActiveDirectoryGroupsResolverTests extends ESTestCase { assertThat(groups, hasItem(containsString("Users"))); } - @Test public void testResolveBaseLevel() throws Exception { Settings settings = Settings.builder() .put("scope", LdapSearchScope.BASE) @@ -100,7 +101,6 @@ public class ActiveDirectoryGroupsResolverTests extends ESTestCase { assertThat(groups, hasItem(containsString("CN=Users,CN=Builtin"))); } - @Test public void testBuildGroupQuery() throws Exception { //test a user with no assigned groups, other than the default groups { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryRealmTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryRealmTests.java index 2bc8c16ef64..1f1f2603c4e 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryRealmTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectoryRealmTests.java @@ -11,23 +11,34 @@ import com.unboundid.ldap.sdk.Attribute; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPURL; import com.unboundid.ldap.sdk.schema.Schema; + import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.User; import org.elasticsearch.shield.authc.RealmConfig; -import org.elasticsearch.shield.authc.support.*; +import org.elasticsearch.shield.authc.support.CachingUsernamePasswordRealm; +import org.elasticsearch.shield.authc.support.DnRoleMapper; +import org.elasticsearch.shield.authc.support.SecuredString; +import org.elasticsearch.shield.authc.support.SecuredStringTests; +import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.shield.authc.ldap.support.SessionFactory.HOSTNAME_VERIFICATION_SETTING; import static org.elasticsearch.shield.authc.ldap.support.SessionFactory.URLS_SETTING; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * Active Directory Realm tests that use the UnboundID In Memory Directory Server @@ -41,7 +52,6 @@ import static org.mockito.Mockito.*; * additional bind DN with a password in the test setup since it really is not a DN in the ldif file */ public class ActiveDirectoryRealmTests extends ESTestCase { - private static final String PASSWORD = "password"; private InMemoryDirectoryServer directoryServer; @@ -76,7 +86,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { directoryServer.shutDown(true); } - @Test public void testAuthenticateUserPrincipleName() throws Exception { Settings settings = settings(); RealmConfig config = new RealmConfig("testAuthenticateUserPrincipleName", settings, globalSettings); @@ -89,7 +98,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { assertThat(user.roles(), arrayContaining(containsString("Avengers"))); } - @Test public void testAuthenticateSAMAccountName() throws Exception { Settings settings = settings(); RealmConfig config = new RealmConfig("testAuthenticateSAMAccountName", settings, globalSettings); @@ -108,7 +116,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { return url.toString(); } - @Test public void testAuthenticateCachesSuccesfulAuthentications() throws Exception { Settings settings = settings(); RealmConfig config = new RealmConfig("testAuthenticateCachesSuccesfulAuthentications", settings, globalSettings); @@ -125,7 +132,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecuredString.class)); } - @Test public void testAuthenticateCachingCanBeDisabled() throws Exception { Settings settings = settings(Settings.builder().put(CachingUsernamePasswordRealm.CACHE_TTL_SETTING, -1).build()); RealmConfig config = new RealmConfig("testAuthenticateCachingCanBeDisabled", settings, globalSettings); @@ -142,7 +148,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecuredString.class)); } - @Test public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Exception { Settings settings = settings(); RealmConfig config = new RealmConfig("testAuthenticateCachingClearsCacheOnRoleMapperRefresh", settings, globalSettings); @@ -168,7 +173,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecuredString.class)); } - @Test public void testRealmMapsGroupsToRoles() throws Exception { Settings settings = settings(Settings.builder() .put(DnRoleMapper.ROLE_MAPPING_FILE_SETTING, getDataPath("role_mapping.yml")) @@ -183,7 +187,6 @@ public class ActiveDirectoryRealmTests extends ESTestCase { assertThat(user.roles(), arrayContaining(equalTo("group_role"))); } - @Test public void testRealmMapsUsersToRoles() throws Exception { Settings settings = settings(Settings.builder() .put(DnRoleMapper.ROLE_MAPPING_FILE_SETTING, getDataPath("role_mapping.yml")) diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectorySessionFactoryTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectorySessionFactoryTests.java index 2b41dbb69ea..6b06d2f9123 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectorySessionFactoryTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/activedirectory/ActiveDirectorySessionFactoryTests.java @@ -19,18 +19,19 @@ import org.elasticsearch.shield.ssl.ClientSSLService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.nio.file.Path; import java.util.List; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; @Network public class ActiveDirectorySessionFactoryTests extends ESTestCase { - public static final String AD_LDAP_URL = "ldaps://54.213.145.20:636"; public static final String PASSWORD = "NickFuryHeartsES"; public static final String AD_DOMAIN = "ad.test.elasticsearch.com"; @@ -56,7 +57,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testAdAuth() throws Exception { RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, false), globalSettings); ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService); @@ -77,7 +78,6 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-shield/issues/499") public void testTcpReadTimeout() throws Exception { Settings settings = Settings.builder() @@ -98,8 +98,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test - public void testAdAuth_avengers() throws Exception { + public void testAdAuthAvengers() throws Exception { RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, false), globalSettings); ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService); @@ -111,7 +110,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testAuthenticate() throws Exception { Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false); RealmConfig config = new RealmConfig("ad-test", settings, globalSettings); @@ -132,8 +131,8 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") - public void testAuthenticate_baseUserSearch() throws Exception { + @SuppressWarnings("unchecked") + public void testAuthenticateBaseUserSearch() throws Exception { Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Bruce Banner, CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.BASE, false); RealmConfig config = new RealmConfig("ad-test", settings, globalSettings); ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService); @@ -153,8 +152,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") - public void testAuthenticate_baseGroupSearch() throws Exception { + public void testAuthenticateBaseGroupSearch() throws Exception { Settings settings = Settings.builder() .put(buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false)) .put(ActiveDirectorySessionFactory.AD_GROUP_SEARCH_BASEDN_SETTING, "CN=Avengers,CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com") @@ -171,7 +169,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testAuthenticateWithUserPrincipalName() throws Exception { Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false); RealmConfig config = new RealmConfig("ad-test", settings, globalSettings); @@ -189,7 +187,6 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test public void testAuthenticateWithSAMAccountName() throws Exception { Settings settings = buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.ONE_LEVEL, false); RealmConfig config = new RealmConfig("ad-test", settings, globalSettings); @@ -208,7 +205,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testCustomUserFilter() throws Exception { Settings settings = Settings.builder() .put(buildAdSettings(AD_LDAP_URL, AD_DOMAIN, "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com", LdapSearchScope.SUB_TREE, false)) @@ -228,7 +225,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testStandardLdapConnection() throws Exception { String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com"; String userTemplate = "CN={0},CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com"; @@ -248,7 +245,7 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testStandardLdapWithAttributeGroups() throws Exception { String userTemplate = "CN={0},CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com"; Settings settings = LdapTestCase.buildLdapSettings(AD_LDAP_URL, userTemplate, false); @@ -267,7 +264,6 @@ public class ActiveDirectorySessionFactoryTests extends ESTestCase { } } - @Test public void testAdAuthWithHostnameVerification() throws Exception { RealmConfig config = new RealmConfig("ad-test", buildAdSettings(AD_LDAP_URL, AD_DOMAIN, true), globalSettings); ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, clientSSLService); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/ESUsersRealmTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/ESUsersRealmTests.java index f5fc1a216c8..e469d375047 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/ESUsersRealmTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/ESUsersRealmTests.java @@ -28,7 +28,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.Before; -import org.junit.Test; import java.util.Locale; @@ -50,7 +49,6 @@ import static org.mockito.Mockito.when; * */ public class ESUsersRealmTests extends ESTestCase { - private Client client; private AdminClient adminClient; private FileUserPasswdStore userPasswdStore; @@ -66,7 +64,6 @@ public class ESUsersRealmTests extends ESTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test public void testAuthenticate() throws Exception { when(userPasswdStore.verifyPassword("user1", SecuredStringTests.build("test123"))).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[] { "role1", "role2" }); @@ -80,8 +77,7 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(user.roles(), arrayContaining("role1", "role2")); } - @Test - public void testAuthenticate_Caching() throws Exception { + public void testAuthenticateCaching() throws Exception { Settings settings = Settings.builder() .put("cache.hash_algo", Hasher.values()[randomIntBetween(0, Hasher.values().length - 1)].name().toLowerCase(Locale.ROOT)) .build(); @@ -94,8 +90,7 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(user1, sameInstance(user2)); } - @Test - public void testAuthenticate_Caching_Refresh() throws Exception { + public void testAuthenticateCachingRefresh() throws Exception { RealmConfig config = new RealmConfig("esusers-test", Settings.EMPTY, globalSettings); userPasswdStore = spy(new UserPasswdStore(config)); userRolesStore = spy(new UserRolesStore(config)); @@ -117,7 +112,6 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(user5, sameInstance(user6)); } - @Test public void testToken() throws Exception { RealmConfig config = new RealmConfig("esusers-test", Settings.EMPTY, globalSettings); when(userPasswdStore.verifyPassword("user1", SecuredStringTests.build("test123"))).thenReturn(true); @@ -134,7 +128,6 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(new String(token.credentials().internalChars()), equalTo("test123")); } - @Test public void testLookup() throws Exception { when(userPasswdStore.userExists("user1")).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[] { "role1", "role2" }); @@ -150,7 +143,6 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(user.roles(), arrayContaining("role1", "role2")); } - @Test public void testLookupCaching() throws Exception { when(userPasswdStore.userExists("user1")).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[] { "role1", "role2" }); @@ -164,7 +156,6 @@ public class ESUsersRealmTests extends ESTestCase { verify(userRolesStore).roles("user1"); } - @Test public void testLookupCachingWithRefresh() throws Exception { RealmConfig config = new RealmConfig("esusers-test", Settings.EMPTY, globalSettings); userPasswdStore = spy(new UserPasswdStore(config)); @@ -187,7 +178,7 @@ public class ESUsersRealmTests extends ESTestCase { assertThat(user5, sameInstance(user6)); } - @Test @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") public void testAuthorizationHeaderIsNotCopied() throws Exception { RestController restController = mock(RestController.class); RealmConfig config = new RealmConfig("esusers-test", Settings.EMPTY, globalSettings); @@ -221,14 +212,12 @@ public class ESUsersRealmTests extends ESTestCase { } static class UserPasswdStore extends FileUserPasswdStore { - public UserPasswdStore(RealmConfig config) { super(config, mock(ResourceWatcherService.class)); } } static class UserRolesStore extends FileUserRolesStore { - public UserRolesStore(RealmConfig config) { super(config, mock(ResourceWatcherService.class)); } diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStoreTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStoreTests.java index d971c5b2718..bcbc7ce2325 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStoreTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/FileUserRolesStoreTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; @@ -26,19 +25,30 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.contains; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * */ public class FileUserRolesStoreTests extends ESTestCase { - private Settings settings; private Environment env; private ThreadPool threadPool; @@ -58,9 +68,7 @@ public class FileUserRolesStoreTests extends ESTestCase { terminate(threadPool); } - @Test public void testStore_ConfiguredWithUnreadableFile() throws Exception { - Path file = createTempFile(); List lines = new ArrayList<>(); lines.add("aldlfkjldjdflkjd"); @@ -78,8 +86,7 @@ public class FileUserRolesStoreTests extends ESTestCase { assertThat(store.entriesCount(), is(0)); } - @Test - public void testStore_AutoReload() throws Exception { + public void testStoreAutoReload() throws Exception { Path users = getDataPath("users_roles"); Path tmp = createTempFile(); Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING); @@ -122,8 +129,7 @@ public class FileUserRolesStoreTests extends ESTestCase { assertThat(roles, arrayContaining("role4", "role5")); } - @Test - public void testStore_AutoReload_WithParseFailure() throws Exception { + public void testStoreAutoReloadWithParseFailure() throws Exception { Path users = getDataPath("users_roles"); Path tmp = createTempFile(); Files.copy(users, tmp, StandardCopyOption.REPLACE_EXISTING); @@ -161,7 +167,6 @@ public class FileUserRolesStoreTests extends ESTestCase { assertThat(store.entriesCount(), is(0)); } - @Test public void testParseFile() throws Exception { Path path = getDataPath("users_roles"); Map usersRoles = FileUserRolesStore.parseFile(path, null); @@ -180,8 +185,7 @@ public class FileUserRolesStoreTests extends ESTestCase { assertThat(usersRoles.get("period.user"), arrayContaining("role4")); } - @Test - public void testParseFile_Empty() throws Exception { + public void testParseFileEmpty() throws Exception { Path empty = createTempFile(); ESLogger log = ESLoggerFactory.getLogger("test"); log = spy(log); @@ -189,8 +193,7 @@ public class FileUserRolesStoreTests extends ESTestCase { verify(log, times(1)).warn(contains("no entries found"), eq(empty.toAbsolutePath())); } - @Test - public void testParseFile_WhenFileDoesNotExist() throws Exception { + public void testParseFileWhenFileDoesNotExist() throws Exception { Path file = createTempDir().resolve(randomAsciiOfLength(10)); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.INFO); Map usersRoles = FileUserRolesStore.parseFile(file, logger); @@ -198,8 +201,7 @@ public class FileUserRolesStoreTests extends ESTestCase { assertThat(usersRoles.isEmpty(), is(true)); } - @Test - public void testParseFile_WhenCannotReadFile() throws Exception { + public void testParseFileWhenCannotReadFile() throws Exception { Path file = createTempFile(); List lines = new ArrayList<>(); lines.add("aldlfkjldjdflkjd"); @@ -215,8 +217,7 @@ public class FileUserRolesStoreTests extends ESTestCase { } } - @Test - public void testParseFile_EmptyRolesDoesNotCauseNPE() throws Exception { + public void testParseFileEmptyRolesDoesNotCauseNPE() throws Exception { ThreadPool threadPool = null; try { threadPool = new ThreadPool("test"); @@ -241,27 +242,23 @@ public class FileUserRolesStoreTests extends ESTestCase { } } - @Test - public void testParseFile_EmptyFileIsParsed() throws Exception { + public void testParseFileEmptyFileIsParsed() throws Exception { assertInvalidInputIsSilentlyIgnored(""); assertInvalidInputIsSilentlyIgnored("#"); } - @Test - public void testParseFile_EmptyRoleNameDoesNotThrowException() throws Exception { + public void testParseFileEmptyRoleNameDoesNotThrowException() throws Exception { assertInvalidInputIsSilentlyIgnored(":user1,user2"); assertInvalidInputIsSilentlyIgnored(" :user1,user2"); } - @Test - public void testParseFile_EmptyRoleDoesNotThrowException() throws Exception { + public void testParseFileEmptyRoleDoesNotThrowException() throws Exception { assertInvalidInputIsSilentlyIgnored("role:"); assertInvalidInputIsSilentlyIgnored("role: "); assertInvalidInputIsSilentlyIgnored("role: , "); } - @Test - public void testParseFileLenient_WhenCannotReadFile() throws Exception { + public void testParseFileLenientWhenCannotReadFile() throws Exception { Path file = createTempFile(); List lines = new ArrayList<>(); lines.add("aldlfkjldjdflkjd"); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java index cea89bc0d60..085a85bf9cb 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.shield.authc.esusers.FileUserRolesStore; import org.elasticsearch.shield.authc.support.Hasher; import org.elasticsearch.shield.authc.support.SecuredStringTests; -import org.junit.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -25,15 +24,27 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; /** * */ public class ESUsersToolTests extends CliToolTestCase { - - @Test - public void testUseradd_Parse_AllOptions() throws Exception { + public void testUseraddParseAllOptions() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("username -p changeme -r r1,r2,r3")); assertThat(command, instanceOf(ESUsersTool.Useradd.class)); @@ -44,7 +55,6 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.roles, arrayContaining("r1", "r2", "r3")); } - @Test public void testUseraddExtraArgs() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("username -p changeme -r r1,r2,r3 r4 r6")); @@ -53,8 +63,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testUseradd_Parse_InvalidUsername() throws Exception { + public void testUseraddParseInvalidUsername() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("$34dkl -p changeme -r r1,r2,r3")); assertThat(command, instanceOf(CliTool.Command.Exit.class)); @@ -62,7 +71,6 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), is(CliTool.ExitStatus.DATA_ERROR)); } - @Test public void testUseradd_Parse_InvalidRoleName() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("username -p changeme -r $343,r2,r3")); @@ -71,8 +79,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), is(CliTool.ExitStatus.DATA_ERROR)); } - @Test - public void testUseradd_Parse_InvalidPassword() throws Exception { + public void testUseraddParseInvalidPassword() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("username -p 123 -r r1,r2,r3")); assertThat(command, instanceOf(CliTool.Command.Exit.class)); @@ -80,16 +87,14 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), is(CliTool.ExitStatus.DATA_ERROR)); } - @Test - public void testUseradd_Parse_NoUsername() throws Exception { + public void testUseraddParseNoUsername() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("useradd", args("-p test123")); assertThat(command, instanceOf(CliTool.Command.Exit.class)); assertThat(((CliTool.Command.Exit) command).status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testUseradd_Parse_NoPassword() throws Exception { + public void testUseraddParseNoPassword() throws Exception { ESUsersTool tool = new ESUsersTool(new MockTerminal() { @Override public char[] readSecret(String text, Object... args) { @@ -105,8 +110,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.roles.length, is(0)); } - @Test - public void testUseradd_Cmd_Create() throws Exception { + public void testUseraddCmdCreate() throws Exception { Path userFile = createTempFile(); Path userRolesFile = createTempFile(); Settings settings = Settings.builder() @@ -137,8 +141,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(lines, containsInAnyOrder("r1:user1", "r2:user1")); } - @Test - public void testUseradd_Cmd_Append() throws Exception { + public void testUseraddCmdAppend() throws Exception { Path userFile = writeFile("user2:hash2"); Path userRolesFile = writeFile("r3:user2\nr4:user2"); Settings settings = Settings.builder() @@ -174,8 +177,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(lines, containsInAnyOrder("r1:user1", "r2:user1", "r3:user2", "r4:user2")); } - @Test - public void testUseradd_Cmd_AddingUserWithoutRolesDoesNotAddEmptyRole() throws Exception { + public void testUseraddCmdAddingUserWithoutRolesDoesNotAddEmptyRole() throws Exception { Path userFile = writeFile("user2:hash2"); Path userRolesFile = writeFile("r3:user2\nr4:user2"); Settings settings = Settings.builder() @@ -196,8 +198,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(lines, not(hasItem(containsString("user1")))); } - @Test - public void testUseradd_Cmd_Append_UserAlreadyExists() throws Exception { + public void testUseraddCmdAppendUserAlreadyExists() throws Exception { Path userFile = writeFile("user1:hash1"); Path userRolesFile = createTempFile(); Settings settings = Settings.builder() @@ -213,9 +214,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(status, is(CliTool.ExitStatus.CODE_ERROR)); } - - @Test - public void testUseradd_CustomRole() throws Exception { + public void testUseraddCustomRole() throws Exception { Path usersFile = createTempFile(); Path userRolesFile = createTempFile(); Path rolesFile = writeFile("plugin_admin:\n" + @@ -236,8 +235,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(terminal.getTerminalOutput(), hasSize(0)); } - @Test - public void testUseradd_NonExistantRole() throws Exception { + public void testUseraddNonExistantRole() throws Exception { Path usersFile = createTempFile(); Path userRolesFile = createTempFile(); Path rolesFile = writeFile("plugin_admin:\n" + @@ -259,8 +257,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(terminal.getTerminalOutput().get(0), containsString("[plugin_admin_2]")); } - @Test - public void testUserdel_Parse() throws Exception { + public void testUserdelParse() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("userdel", args("username")); assertThat(command, instanceOf(ESUsersTool.Userdel.class)); @@ -268,8 +265,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userdel.username, equalTo("username")); } - @Test - public void testUserdel_Parse_MissingUsername() throws Exception { + public void testUserdelParseMissingUsername() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("userdel", args(null)); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -277,8 +273,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), equalTo(CliTool.ExitStatus.USAGE)); } - @Test - public void testUserdel_Parse_ExtraArgs() throws Exception { + public void testUserdelParseExtraArgs() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("userdel", args("user1 user2")); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -286,8 +281,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(exit.status(), equalTo(CliTool.ExitStatus.USAGE)); } - @Test - public void testUserdel_Cmd() throws Exception { + public void testUserdelCmd() throws Exception { Path userFile = writeFile("user1:hash2"); Path userRolesFile = writeFile("r3:user1\nr4:user1"); Settings settings = Settings.builder() @@ -311,8 +305,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(lines.size(), is(0)); } - @Test - public void testUserdel_Cmd_MissingUser() throws Exception { + public void testUserdelCmdMissingUser() throws Exception { Path userFile = writeFile("user1:hash2"); Path userRolesFile = writeFile("r3:user1\nr4:user1"); Settings settings = Settings.builder() @@ -341,8 +334,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(lines, hasSize(2)); } - @Test - public void testUserdel_Cmd_MissingFiles() throws Exception { + public void testUserdelCmdMissingFiles() throws Exception { Path dir = createTempDir(); Path userFile = dir.resolve("users"); Path userRolesFile = dir.resolve("users_roles"); @@ -362,8 +354,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(Files.exists(userRolesFile), is(false)); } - @Test - public void testPasswd_Parse_AllOptions() throws Exception { + public void testPasswdParseAllOptions() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("passwd", args("user1 -p changeme")); assertThat(command, instanceOf(ESUsersTool.Passwd.class)); @@ -372,8 +363,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(new String(cmd.passwd.internalChars()), equalTo("changeme")); } - @Test - public void testPasswd_Parse_MissingUsername() throws Exception { + public void testPasswdParseMissingUsername() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("passwd", args("-p changeme")); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -381,8 +371,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testPasswd_Parse_ExtraArgs() throws Exception { + public void testPasswdParseExtraArgs() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("passwd", args("user1 user2 -p changeme")); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -390,8 +379,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testPasswd_Parse_MissingPassword() throws Exception { + public void testPasswdParseMissingPassword() throws Exception { final AtomicReference secretRequested = new AtomicReference<>(false); Terminal terminal = new MockTerminal() { @Override @@ -409,8 +397,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(secretRequested.get(), is(true)); } - @Test - public void testPasswd_Cmd() throws Exception { + public void testPasswdCmd() throws Exception { Path userFile = writeFile("user1:hash2"); Settings settings = Settings.builder() .put("shield.authc.realms.esusers.type", "esusers") @@ -432,8 +419,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(Hasher.BCRYPT.verify(SecuredStringTests.build("changeme"), hash.toCharArray()), is(true)); } - @Test - public void testPasswd_Cmd_UnknownUser() throws Exception { + public void testPasswdCmdUnknownUser() throws Exception { Path userFile = writeFile("user1:hash2"); Settings settings = Settings.builder() .put("shield.authc.realms.esusers.type", "esusers") @@ -446,8 +432,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(status, is(CliTool.ExitStatus.NO_USER)); } - @Test - public void testPasswd_Cmd_MissingFiles() throws Exception { + public void testPasswdCmdMissingFiles() throws Exception { Path userFile = createTempFile(); Settings settings = Settings.builder() .put("shield.authc.realms.esusers.type", "esusers") @@ -460,8 +445,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(status, is(CliTool.ExitStatus.NO_USER)); } - @Test - public void testRoles_Parse_AllOptions() throws Exception { + public void testRolesParseAllOptions() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("roles", args("someuser -a test1,test2,test3 -r test4,test5,test6")); assertThat(command, instanceOf(ESUsersTool.Roles.class)); @@ -471,8 +455,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(rolesCommand.removeRoles, arrayContaining("test4", "test5", "test6")); } - @Test - public void testRoles_Parse_ExtraArgs() throws Exception { + public void testRolesParseExtraArgs() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("roles", args("someuser -a test1,test2,test3 foo -r test4,test5,test6 bar")); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -480,8 +463,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testRoles_Cmd_validatingRoleNames() throws Exception { + public void testRolesCmdValidatingRoleNames() throws Exception { ESUsersTool tool = new ESUsersTool(); Path usersFile = writeFile("admin:hash"); Path usersRoleFile = writeFile("admin: admin\n"); @@ -507,8 +489,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(execute(tool.parse("roles", args("admin -a role0")), settings), is(CliTool.ExitStatus.OK)); } - @Test - public void testRoles_Cmd_addingRoleWorks() throws Exception { + public void testRolesCmdAddingRoleWorks() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser: user\n"); Settings settings = Settings.builder() @@ -530,8 +511,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userRoles.get("user"), arrayContainingInAnyOrder("user", "foo")); } - @Test - public void testRoles_Cmd_removingRoleWorks() throws Exception { + public void testRolesCmdRemovingRoleWorks() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo: user\nbar: user\n"); Settings settings = Settings.builder() @@ -553,8 +533,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userRoles.get("user"), arrayContainingInAnyOrder("user", "bar")); } - @Test - public void testRoles_Cmd_addingAndRemovingRoleWorks() throws Exception { + public void testRolesCmdAddingAndRemovingRoleWorks() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser:user\nfoo:user\nbar:user\n"); Settings settings = Settings.builder() @@ -576,8 +555,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userRoles.get("user"), arrayContainingInAnyOrder("user", "bar", "newrole")); } - @Test - public void testRoles_Cmd_removingLastRoleRemovesEntryFromRolesFile() throws Exception { + public void testRolesCmdRemovingLastRoleRemovesEntryFromRolesFile() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser:user\nfoo:user\nbar:user\n"); Settings settings = Settings.builder() @@ -596,8 +574,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(usersRoleFileLines, not(hasItem(containsString("user")))); } - @Test - public void testRoles_Cmd_userNotFound() throws Exception { + public void testRolesCmdUserNotFound() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Settings settings = Settings.builder() @@ -613,8 +590,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(status, is(CliTool.ExitStatus.NO_USER)); } - @Test - public void testRoles_Cmd_testNotAddingOrRemovingRolesShowsListingOfRoles() throws Exception { + public void testRolesCmdTestNotAddingOrRemovingRolesShowsListingOfRoles() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\nuser:user\nfoo:user\nbar:user\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all\n\nfoo:\n cluster: all\n\nbar:\n cluster: all"); @@ -634,8 +610,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(allOf(containsString("user"), containsString("user,foo,bar")))); } - @Test - public void testRoles_cmd_testRoleCanBeAddedWhenUserIsNotInRolesFile() throws Exception { + public void testRolesCmdRoleCanBeAddedWhenUserIsNotInRolesFile() throws Exception { Path usersFile = writeFile("admin:hash\nuser:hash"); Path usersRoleFile = writeFile("admin: admin\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nmyrole:\n cluster: all"); @@ -658,8 +633,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userRoles.get("user"), arrayContaining("myrole")); } - @Test - public void testListUsersAndRoles_Cmd_parsingWorks() throws Exception { + public void testListUsersAndRolesCmdParsingWorks() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("list", args("someuser")); assertThat(command, instanceOf(ESUsersTool.ListUsersAndRoles.class)); @@ -667,8 +641,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(listUsersAndRolesCommand.username, is("someuser")); } - @Test - public void testListUsersAndRoles_Cmd_parsingExtraArgs() throws Exception { + public void testListUsersAndRolesCmdParsingExtraArgs() throws Exception { ESUsersTool tool = new ESUsersTool(); CliTool.Command command = tool.parse("list", args("someuser two")); assertThat(command, instanceOf(ESUsersTool.Command.Exit.class)); @@ -676,8 +649,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(cmd.status(), is(CliTool.ExitStatus.USAGE)); } - @Test - public void testListUsersAndRoles_Cmd_listAllUsers() throws Exception { + public void testListUsersAndRolesCmdListAllUsers() throws Exception { Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all\n\nfoo:\n cluster: all\n\nbar:\n cluster: all"); Settings settings = Settings.builder() @@ -697,8 +669,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(allOf(containsString("user"), containsString("user,foo,bar")))); } - @Test - public void testListUsersAndRoles_Cmd_listAllUsers_WithUnknownRoles() throws Exception { + public void testListUsersAndRolesCmdListAllUsersWithUnknownRoles() throws Exception { Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all"); Settings settings = Settings.builder() @@ -718,8 +689,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(allOf(containsString("user"), containsString("user,foo*,bar*")))); } - @Test - public void testListUsersAndRoles_Cmd_listSingleUser() throws Exception { + public void testListUsersAndRolesCmdListSingleUser() throws Exception { Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Path usersFile = writeFile("admin:{plain}changeme\nuser:{plain}changeme\nno-roles-user:{plain}changeme\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all\n\nfoo:\n cluster: all"); @@ -741,8 +711,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(not(containsString("user")))); } - @Test - public void testListUsersAndRoles_Cmd_NoUsers() throws Exception { + public void testListUsersAndRolesCmdNoUsers() throws Exception { Path usersFile = writeFile(""); Path usersRoleFile = writeFile(""); Settings settings = Settings.builder() @@ -762,8 +731,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(output.get(0), equalTo("No users found" + System.lineSeparator())); } - @Test - public void testListUsersAndRoles_Cmd_listSingleUserNotFound() throws Exception { + public void testListUsersAndRolesCmdListSingleUserNotFound() throws Exception { Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Settings settings = Settings.builder() .put("shield.authc.realms.esusers.type", "esusers") @@ -778,8 +746,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(status, is(CliTool.ExitStatus.NO_USER)); } - @Test - public void testListUsersAndRoles_Cmd_testThatUsersWithAndWithoutRolesAreListed() throws Exception { + public void testListUsersAndRolesCmdUsersWithAndWithoutRolesAreListed() throws Exception { Path usersFile = writeFile("admin:{plain}changeme\nuser:{plain}changeme\nno-roles-user:{plain}changeme\n"); Path usersRoleFile = writeFile("admin: admin\nuser: user\nfoo:user\nbar:user\n"); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all\n\nfoo:\n cluster: all\n\nbar:\n cluster: all"); @@ -802,8 +769,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(allOf(containsString("no-roles-user"), containsString("-")))); } - @Test - public void testListUsersAndRoles_Cmd_testThatUsersWithoutRolesAreListed() throws Exception { + public void testListUsersAndRolesCmdUsersWithoutRolesAreListed() throws Exception { Path usersFile = writeFile("admin:{plain}changeme\nuser:{plain}changeme\nno-roles-user:{plain}changeme\n"); Path usersRoleFile = writeFile(""); Path rolesFile = writeFile("admin:\n cluster: all\n\nuser:\n cluster: all\n\nfoo:\n cluster: all\n\nbar:\n cluster: all"); @@ -826,8 +792,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(catchTerminalOutput.getTerminalOutput(), hasItem(allOf(containsString("no-roles-user"), containsString("-")))); } - @Test - public void testListUsersAndRoles_Cmd_testThatUsersWithoutRolesAreListedForSingleUser() throws Exception { + public void testListUsersAndRolesCmdUsersWithoutRolesAreListedForSingleUser() throws Exception { Path usersFile = writeFile("admin:{plain}changeme"); Path usersRoleFile = writeFile(""); Settings settings = Settings.builder() @@ -846,8 +811,7 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(loggingTerminal.getTerminalOutput(), hasItem(allOf(containsString("admin"), containsString("-")))); } - @Test - public void testUseradd_UsernameWithPeriod() throws Exception { + public void testUseraddUsernameWithPeriod() throws Exception { Path userFile = createTempFile(); Path userRolesFile = createTempFile(); Settings settings = Settings.builder() diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapRealmTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapRealmTests.java index 48f7bab0fb7..475bfba6ff7 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapRealmTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapRealmTests.java @@ -19,18 +19,22 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.shield.authc.ldap.LdapSessionFactory.USER_DN_TEMPLATES_SETTING; import static org.elasticsearch.shield.authc.ldap.support.SessionFactory.HOSTNAME_VERIFICATION_SETTING; import static org.elasticsearch.shield.authc.ldap.support.SessionFactory.URLS_SETTING; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; public class LdapRealmTests extends LdapTestCase { - public static final String VALID_USER_TEMPLATE = "cn={0},ou=people,o=sevenSeas"; public static final String VALID_USERNAME = "Thomas Masterman Hardy"; public static final String PASSWORD = "pass"; @@ -52,8 +56,7 @@ public class LdapRealmTests extends LdapTestCase { terminate(threadPool); } - @Test - public void testAuthenticate_SubTreeGroupSearch() throws Exception { + public void testAuthenticateSubTreeGroupSearch() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; Settings settings = buildLdapSettings(ldapUrl(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE); @@ -66,8 +69,7 @@ public class LdapRealmTests extends LdapTestCase { assertThat(user.roles(), arrayContaining("HMS Victory")); } - @Test - public void testAuthenticate_OneLevelGroupSearch() throws Exception { + public void testAuthenticateOneLevelGroupSearch() throws Exception { String groupSearchBase = "ou=crews,ou=groups,o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; Settings settings = Settings.builder() @@ -83,8 +85,7 @@ public class LdapRealmTests extends LdapTestCase { assertThat(user.roles(), arrayContaining("HMS Victory")); } - @Test - public void testAuthenticate_Caching() throws Exception { + public void testAuthenticateCaching() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; Settings settings = Settings.builder() @@ -102,8 +103,7 @@ public class LdapRealmTests extends LdapTestCase { verify(ldapFactory, times(1)).session(anyString(), any(SecuredString.class)); } - @Test - public void testAuthenticate_Caching_Refresh() throws Exception { + public void testAuthenticateCachingRefresh() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; Settings settings = Settings.builder() @@ -129,8 +129,7 @@ public class LdapRealmTests extends LdapTestCase { verify(ldapFactory, times(2)).session(anyString(), any(SecuredString.class)); } - @Test - public void testAuthenticate_Noncaching() throws Exception { + public void testAuthenticateNoncaching() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; Settings settings = Settings.builder() @@ -149,7 +148,6 @@ public class LdapRealmTests extends LdapTestCase { verify(ldapFactory, times(2)).session(anyString(), any(SecuredString.class)); } - @Test public void testLdapRealmSelectsLdapSessionFactory() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; @@ -165,7 +163,6 @@ public class LdapRealmTests extends LdapTestCase { assertThat(sessionFactory, is(instanceOf(LdapSessionFactory.class))); } - @Test public void testLdapRealmSelectsLdapUserSearchSessionFactory() throws Exception { String groupSearchBase = "o=sevenSeas"; Settings settings = Settings.builder() @@ -186,7 +183,6 @@ public class LdapRealmTests extends LdapTestCase { } } - @Test public void testLdapRealmThrowsExceptionForUserTemplateAndSearchSettings() throws Exception { Settings settings = Settings.builder() .putArray(URLS_SETTING, ldapUrl()) @@ -205,7 +201,6 @@ public class LdapRealmTests extends LdapTestCase { } } - @Test public void testLdapRealmMapsUserDNToRole() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = VALID_USER_TEMPLATE; diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapSessionFactoryTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapSessionFactoryTests.java index 2b2d27ec9b6..6ec08bca204 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapSessionFactoryTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapSessionFactoryTests.java @@ -16,15 +16,17 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.SecuredStringTests; import org.elasticsearch.test.junit.annotations.Network; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.util.List; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; public class LdapSessionFactoryTests extends LdapTestCase { - private Settings globalSettings; @Before @@ -32,7 +34,6 @@ public class LdapSessionFactoryTests extends LdapTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test public void testBindWithReadTimeout() throws Exception { String ldapUrl = ldapUrl(); String groupSearchBase = "o=sevenSeas"; @@ -61,7 +62,6 @@ public class LdapSessionFactoryTests extends LdapTestCase { } } - @Test @Network @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch-shield/issues/767") public void testConnectTimeout() { @@ -92,7 +92,6 @@ public class LdapSessionFactoryTests extends LdapTestCase { } } - @Test public void testBindWithTemplates() throws Exception { String groupSearchBase = "o=sevenSeas"; String[] userTemplates = new String[] { @@ -113,8 +112,6 @@ public class LdapSessionFactoryTests extends LdapTestCase { } } - - @Test(expected = ElasticsearchSecurityException.class) public void testBindWithBogusTemplates() throws Exception { String groupSearchBase = "o=sevenSeas"; String[] userTemplates = new String[] { @@ -129,11 +126,13 @@ public class LdapSessionFactoryTests extends LdapTestCase { String user = "Horatio Hornblower"; SecuredString userPass = SecuredStringTests.build("pass"); try (LdapSession ldapConnection = ldapFac.session(user, userPass)) { + fail("Expected ElasticsearchSecurityException"); + } catch (ElasticsearchSecurityException e) { + assertThat(e.getMessage(), is("failed LDAP authentication")); } } - @Test - public void testGroupLookup_Subtree() throws Exception { + public void testGroupLookupSubtree() throws Exception { String groupSearchBase = "o=sevenSeas"; String userTemplate = "cn={0},ou=people,o=sevenSeas"; RealmConfig config = new RealmConfig("ldap_realm", buildLdapSettings(ldapUrl(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE), globalSettings); @@ -149,8 +148,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { } } - @Test - public void testGroupLookup_OneLevel() throws Exception { + public void testGroupLookupOneLevel() throws Exception { String groupSearchBase = "ou=crews,ou=groups,o=sevenSeas"; String userTemplate = "cn={0},ou=people,o=sevenSeas"; RealmConfig config = new RealmConfig("ldap_realm", buildLdapSettings(ldapUrl(), userTemplate, groupSearchBase, LdapSearchScope.ONE_LEVEL), globalSettings); @@ -164,8 +162,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { } } - @Test - public void testGroupLookup_Base() throws Exception { + public void testGroupLookupBase() throws Exception { String groupSearchBase = "cn=HMS Lydia,ou=crews,ou=groups,o=sevenSeas"; String userTemplate = "cn={0},ou=people,o=sevenSeas"; RealmConfig config = new RealmConfig("ldap_realm", buildLdapSettings(ldapUrl(), userTemplate, groupSearchBase, LdapSearchScope.BASE), globalSettings); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapUserSearchSessionFactoryTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapUserSearchSessionFactoryTests.java index b1850fa10bd..2c9e2392e6e 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapUserSearchSessionFactoryTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/LdapUserSearchSessionFactoryTests.java @@ -7,8 +7,14 @@ package org.elasticsearch.shield.authc.ldap; import com.carrotsearch.randomizedtesting.ThreadFilter; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; -import com.unboundid.ldap.sdk.*; -import org.elasticsearch.*; +import com.unboundid.ldap.sdk.BindRequest; +import com.unboundid.ldap.sdk.GetEntryLDAPConnectionPoolHealthCheck; +import com.unboundid.ldap.sdk.LDAPConnectionPool; +import com.unboundid.ldap.sdk.LDAPConnectionPoolHealthCheck; +import com.unboundid.ldap.sdk.SimpleBindRequest; +import com.unboundid.ldap.sdk.SingleServerSet; + +import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.Version; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; @@ -29,15 +35,22 @@ import org.elasticsearch.shield.ssl.ClientSSLService; import org.elasticsearch.shield.support.NoOpLogger; import org.elasticsearch.test.junit.annotations.Network; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.text.MessageFormat; -import java.util.*; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; // thread leak filter for UnboundID's background connect threads. The background connect threads do not always respect the // timeout and linger. Will be fixed in a new version of the library, see http://sourceforge.net/p/ldap-sdk/discussion/1001257/thread/154e3b71/ @@ -45,7 +58,6 @@ import static org.hamcrest.Matchers.*; LdapUserSearchSessionFactoryTests.BackgroundConnectThreadLeakFilter.class }) public class LdapUserSearchSessionFactoryTests extends LdapTestCase { - private ClientSSLService clientSSLService; private Settings globalSettings; @@ -67,8 +79,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { globalSettings = settingsBuilder().put("path.home", createTempDir()).build(); } - @Test - public void supportsUnauthenticatedSessions() throws Exception { + public void testSupportsUnauthenticatedSessions() throws Exception { RealmConfig config = new RealmConfig("ldap_realm", settingsBuilder() .put(buildLdapSettings(ldapUrl(), Strings.EMPTY_ARRAY, "", LdapSearchScope.SUB_TREE)) .put("user_search.base_dn", "") @@ -85,7 +96,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchSubTree() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -120,7 +130,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchBaseScopeFailsWithWrongBaseDN() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -158,7 +167,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchBaseScopePassesWithCorrectBaseDN() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "cn=William Bush,ou=people,o=sevenSeas"; @@ -194,7 +202,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchOneLevelScopeFailsWithWrongBaseDN() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -232,7 +239,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchOneLevelScopePassesWithCorrectBaseDN() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "ou=people,o=sevenSeas"; @@ -268,7 +274,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchWithBadAttributeFails() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -305,7 +310,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testUserSearchWithoutAttributePasses() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -339,7 +343,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test @Network + @Network public void testUserSearchWithActiveDirectory() throws Exception { String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com"; String userSearchBase = "CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com"; @@ -381,7 +385,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test @Network + @Network public void testUserSearchwithBindUserOpenLDAP() throws Exception { String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; String userSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; @@ -413,7 +417,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testConnectionPoolDefaultSettings() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -437,7 +440,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testConnectionPoolSettings() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -462,7 +464,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testThatEmptyBindDNThrowsExceptionWithHealthCheckEnabled() throws Exception { String groupSearchBase = "o=sevenSeas"; String userSearchBase = "o=sevenSeas"; @@ -479,13 +480,11 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } } - @Test public void testEmptyBindDNReturnsNullBindRequest() { BindRequest request = LdapUserSearchSessionFactory.bindRequest(settingsBuilder().put("bind_password", "password").build()); assertThat(request, is(nullValue())); } - @Test public void testThatBindRequestReturnsSimpleBindRequest() { BindRequest request = LdapUserSearchSessionFactory.bindRequest(settingsBuilder() .put("bind_password", "password") @@ -496,7 +495,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { assertThat(simpleBindRequest.getBindDN(), is("cn=ironman")); } - @Test @Network public void testThatLDAPServerConnectErrorDoesNotPreventNodeFromStarting() { String groupSearchBase = "DC=ad,DC=test,DC=elasticsearch,DC=com"; @@ -523,7 +521,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { } public static class BackgroundConnectThreadLeakFilter implements ThreadFilter { - @Override public boolean reject(Thread thread) { if (thread.getName().startsWith("Background connect thread for elastic.co")) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/OpenLdapTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/OpenLdapTests.java index 3da7919f074..7d51a1142c8 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/OpenLdapTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/OpenLdapTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.shield.ssl.ClientSSLService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.nio.file.Path; @@ -53,7 +52,6 @@ public class OpenLdapTests extends ESTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test public void testConnect() throws Exception { //openldap does not use cn as naming attributes by default String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; @@ -69,7 +67,6 @@ public class OpenLdapTests extends ESTestCase { } } - @Test public void testGroupSearchScopeBase() throws Exception { //base search on a groups means that the user can be in just one group @@ -86,7 +83,6 @@ public class OpenLdapTests extends ESTestCase { } } - @Test public void testCustomFilter() throws Exception { String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; String userTemplate = "uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; @@ -103,7 +99,6 @@ public class OpenLdapTests extends ESTestCase { } } - @Test @AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-shield/issues/499") public void testTcpTimeout() throws Exception { String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; @@ -125,7 +120,6 @@ public class OpenLdapTests extends ESTestCase { } } - @Test public void testStandardLdapConnectionHostnameVerification() throws Exception { //openldap does not use cn as naming attributes by default String groupSearchBase = "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com"; diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/SearchGroupsResolverTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/SearchGroupsResolverTests.java index b83d498c2ec..898c38c22b1 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/SearchGroupsResolverTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/SearchGroupsResolverTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.shield.authc.ldap; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.ldap.sdk.LDAPURL; + import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; @@ -20,12 +21,15 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.util.List; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; @Network public class SearchGroupsResolverTests extends ESTestCase { @@ -55,13 +59,13 @@ public class SearchGroupsResolverTests extends ESTestCase { ldapConnection = new LDAPConnection(clientSSLService.sslSocketFactory(), options, ldapurl.getHost(), ldapurl.getPort(), BRUCE_BANNER_DN, OpenLdapTests.PASSWORD); } + @Override @After public void tearDown() throws Exception { super.tearDown(); ldapConnection.close(); } - @Test public void testResolveSubTree() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -76,7 +80,6 @@ public class SearchGroupsResolverTests extends ESTestCase { containsString("Philanthropists"))); } - @Test public void testResolveOneLevel() throws Exception { Settings settings = Settings.builder() .put("base_dn", "ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -92,7 +95,6 @@ public class SearchGroupsResolverTests extends ESTestCase { containsString("Philanthropists"))); } - @Test public void testResolveBase() throws Exception { Settings settings = Settings.builder() .put("base_dn", "cn=Avengers,ou=People,dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -104,7 +106,6 @@ public class SearchGroupsResolverTests extends ESTestCase { assertThat(groups, hasItem(containsString("Avengers"))); } - @Test public void testResolveCustomFilter() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -117,7 +118,6 @@ public class SearchGroupsResolverTests extends ESTestCase { assertThat(groups, hasItem(containsString("Geniuses"))); } - @Test public void testCreateWithoutSpecifyingBaseDN() throws Exception { Settings settings = Settings.builder() .put("scope", LdapSearchScope.SUB_TREE) @@ -131,7 +131,6 @@ public class SearchGroupsResolverTests extends ESTestCase { } } - @Test public void testReadUserAttributeUid() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -140,7 +139,6 @@ public class SearchGroupsResolverTests extends ESTestCase { assertThat(resolver.readUserAttribute(ldapConnection, BRUCE_BANNER_DN, TimeValue.timeValueSeconds(5), NoOpLogger.INSTANCE), is("hulk")); } - @Test public void testReadUserAttributeCn() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -150,7 +148,6 @@ public class SearchGroupsResolverTests extends ESTestCase { assertThat(resolver.readUserAttribute(ldapConnection, BRUCE_BANNER_DN, TimeValue.timeValueSeconds(5), NoOpLogger.INSTANCE), is("Bruce Banner")); } - @Test public void testReadNonExistentUserAttribute() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") @@ -165,7 +162,6 @@ public class SearchGroupsResolverTests extends ESTestCase { } } - @Test public void testReadBinaryUserAttribute() throws Exception { Settings settings = Settings.builder() .put("base_dn", "dc=oldap,dc=test,dc=elasticsearch,dc=com") diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/UserAttributeGroupsResolverTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/UserAttributeGroupsResolverTests.java index 1a336bb988a..c97ac70707c 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/UserAttributeGroupsResolverTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/UserAttributeGroupsResolverTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.shield.authc.ldap; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.ldap.sdk.LDAPURL; + import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; @@ -19,18 +20,21 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.util.List; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItems; @Network public class UserAttributeGroupsResolverTests extends ESTestCase { public static final String BRUCE_BANNER_DN = "cn=Bruce Banner,CN=Users,DC=ad,DC=test,DC=elasticsearch,DC=com"; private LDAPConnection ldapConnection; + @Override @Before public void setUp() throws Exception { super.setUp(); @@ -53,13 +57,13 @@ public class UserAttributeGroupsResolverTests extends ESTestCase { ldapConnection = new LDAPConnection(clientSSLService.sslSocketFactory(), options, ldapurl.getHost(), ldapurl.getPort(), BRUCE_BANNER_DN, ActiveDirectorySessionFactoryTests.PASSWORD); } + @Override @After public void tearDown() throws Exception { super.tearDown(); ldapConnection.close(); } - @Test public void testResolve() throws Exception { //falling back on the 'memberOf' attribute UserAttributeGroupsResolver resolver = new UserAttributeGroupsResolver(Settings.EMPTY); @@ -71,7 +75,6 @@ public class UserAttributeGroupsResolverTests extends ESTestCase { containsString("Philanthropists"))); } - @Test public void testResolveCustomGroupAttribute() throws Exception { Settings settings = Settings.builder() .put("user_group_attribute", "seeAlso") @@ -81,7 +84,6 @@ public class UserAttributeGroupsResolverTests extends ESTestCase { assertThat(groups, hasItems(containsString("Avengers"))); //seeAlso only has Avengers } - @Test public void testResolveInvalidGroupAttribute() throws Exception { Settings settings = Settings.builder() .put("user_group_attribute", "doesntExist") diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/LDAPServersTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/LDAPServersTests.java index 0d343ee9344..3010b4a7559 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/LDAPServersTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/LDAPServersTests.java @@ -6,15 +6,13 @@ package org.elasticsearch.shield.authc.ldap.support; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class LDAPServersTests extends ESTestCase { - - @Test - public void testConfigure_1ldaps() { + public void testConfigure1ldaps() { String[] urls = new String[] { "ldaps://example.com:636" }; SessionFactory.LDAPServers servers = new SessionFactory.LDAPServers(urls); @@ -25,8 +23,7 @@ public class LDAPServersTests extends ESTestCase { assertThat(servers.ssl(), is(equalTo(true))); } - @Test - public void testConfigure_2ldaps() { + public void testConfigure2ldaps() { String[] urls = new String[] { "ldaps://primary.example.com:636", "LDAPS://secondary.example.com:10636" }; SessionFactory.LDAPServers servers = new SessionFactory.LDAPServers(urls); @@ -39,8 +36,7 @@ public class LDAPServersTests extends ESTestCase { assertThat(servers.ssl(), is(equalTo(true))); } - @Test - public void testConfigure_2ldap() { + public void testConfigure2ldap() { String[] urls = new String[] { "ldap://primary.example.com:392", "LDAP://secondary.example.com:10392" }; SessionFactory.LDAPServers servers = new SessionFactory.LDAPServers(urls); @@ -53,17 +49,25 @@ public class LDAPServersTests extends ESTestCase { assertThat(servers.ssl(), is(equalTo(false))); } - @Test(expected = IllegalArgumentException.class) - public void testConfigure_1ldaps_1ldap() { + public void testConfigure1ldaps1ldap() { String[] urls = new String[] { "LDAPS://primary.example.com:636", "ldap://secondary.example.com:392" }; - new SessionFactory.LDAPServers(urls); + try { + new SessionFactory.LDAPServers(urls); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("configured LDAP protocols are not all equal")); + } } - @Test(expected = IllegalArgumentException.class) - public void testConfigure_1ldap_1ldaps() { + public void testConfigure1ldap1ldaps() { String[] urls = new String[] { "ldap://primary.example.com:392", "ldaps://secondary.example.com:636" }; - new SessionFactory.LDAPServers(urls); + try { + new SessionFactory.LDAPServers(urls); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("configured LDAP protocols are not all equal")); + } } } diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/SessionFactoryTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/SessionFactoryTests.java index 62d17e6d869..81e9af96380 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/SessionFactoryTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/ldap/support/SessionFactoryTests.java @@ -8,19 +8,19 @@ package org.elasticsearch.shield.authc.ldap.support; import com.unboundid.ldap.sdk.LDAPConnectionOptions; import com.unboundid.util.ssl.HostNameSSLSocketVerifier; import com.unboundid.util.ssl.TrustAllSSLSocketVerifier; + import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.RealmConfig; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; public class SessionFactoryTests extends ESTestCase { - - @Test - public void connectionFactoryReturnsCorrectLDAPConnectionOptionsWithDefaultSettings() { + public void testConnectionFactoryReturnsCorrectLDAPConnectionOptionsWithDefaultSettings() { SessionFactory factory = createSessionFactory(); LDAPConnectionOptions options = SessionFactory.connectionOptions(Settings.EMPTY); assertThat(options.followReferrals(), is(equalTo(true))); @@ -30,8 +30,7 @@ public class SessionFactoryTests extends ESTestCase { assertThat(options.getSSLSocketVerifier(), is(instanceOf(HostNameSSLSocketVerifier.class))); } - @Test - public void connectionFactoryReturnsCorrectLDAPConnectionOptions() { + public void testConnectionFactoryReturnsCorrectLDAPConnectionOptions() { Settings settings = settingsBuilder() .put(SessionFactory.TIMEOUT_TCP_CONNECTION_SETTING, "10ms") .put(SessionFactory.HOSTNAME_VERIFICATION_SETTING, "false") @@ -47,13 +46,11 @@ public class SessionFactoryTests extends ESTestCase { assertThat(options.getSSLSocketVerifier(), is(instanceOf(TrustAllSSLSocketVerifier.class))); } - @Test - public void sessionFactoryDoesNotSupportUnauthenticated() { + public void testSessionFactoryDoesNotSupportUnauthenticated() { assertThat(createSessionFactory().supportsUnauthenticatedSession(), is(false)); } - @Test - public void unauthenticatedSessionThrowsUnsupportedOperationException() throws Exception { + public void testUnauthenticatedSessionThrowsUnsupportedOperationException() throws Exception { try { createSessionFactory().unauthenticatedSession(randomAsciiOfLength(5)); fail("session factory should throw an unsupported operation exception"); @@ -61,6 +58,7 @@ public class SessionFactoryTests extends ESTestCase { // expected... } } + private SessionFactory createSessionFactory() { Settings global = settingsBuilder().put("path.home", createTempDir()).build(); return new SessionFactory(new RealmConfig("_name", Settings.EMPTY, global)) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiAuthenticationTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiAuthenticationTests.java index bcafc2b12e0..0c8f479aebd 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiAuthenticationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiAuthenticationTests.java @@ -25,11 +25,7 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.transport.Transport; -import org.junit.Test; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -37,14 +33,19 @@ import java.security.KeyStore; import java.security.SecureRandom; import java.util.Locale; -import static org.hamcrest.Matchers.*; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; /** * Test authentication via PKI on both REST and Transport layers */ @ClusterScope(numClientNodes = 0, numDataNodes = 1) public class PkiAuthenticationTests extends ShieldIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -67,7 +68,6 @@ public class PkiAuthenticationTests extends ShieldIntegTestCase { return true; } - @Test public void testTransportClientCanAuthenticateViaPki() { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.jks", "testnode"); try (TransportClient client = createTransportClient(settings)) { @@ -81,16 +81,16 @@ public class PkiAuthenticationTests extends ShieldIntegTestCase { * Test uses the testclient cert which is trusted by the SSL layer BUT it is not trusted by the PKI authentication * realm */ - @Test(expected = NoNodeAvailableException.class) public void testTransportClientAuthenticationFailure() { try (TransportClient client = createTransportClient(Settings.EMPTY)) { client.addTransportAddress(randomFrom(internalCluster().getInstance(Transport.class).boundAddress().boundAddresses())); client.prepareIndex("foo", "bar").setSource("pki", "auth").get(); fail("transport client should not have been able to authenticate"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#")); } } - @Test public void testRestAuthenticationViaPki() throws Exception { SSLContext context = getRestSSLContext("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.jks", "testnode"); try (CloseableHttpClient client = HttpClients.custom().setSslcontext(context).build()) { @@ -102,7 +102,6 @@ public class PkiAuthenticationTests extends ShieldIntegTestCase { } } - @Test public void testRestAuthenticationFailure() throws Exception { SSLContext context = getRestSSLContext("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient.jks", "testclient"); try (CloseableHttpClient client = HttpClients.custom().setSslcontext(context).build()) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index e884216fa63..8769004b0fa 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -23,10 +23,7 @@ import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.transport.Transport; import org.junit.BeforeClass; -import org.junit.Test; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; import java.io.InputStream; import java.net.InetAddress; import java.nio.file.Files; @@ -34,6 +31,9 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.SecureRandom; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_PASSWORD; import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_USER_NAME; import static org.hamcrest.Matchers.is; @@ -74,7 +74,6 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { return true; } - @Test public void testRestClientWithoutClientCertificate() throws Exception { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); @@ -94,7 +93,6 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { } } - @Test public void testTransportClientWithoutClientCertificate() { Transport transport = internalCluster().getDataNodeInstance(Transport.class); int port = ((InetSocketTransportAddress) randomFrom(transport.profileBoundAddresses().get("want_client_auth").boundAddresses())).address().getPort(); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiRealmTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiRealmTests.java index cb742840a86..fbf533978ce 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiRealmTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiRealmTests.java @@ -17,9 +17,7 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.transport.TransportMessage; import org.junit.Before; -import org.junit.Test; -import javax.security.auth.x500.X500Principal; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -28,11 +26,18 @@ import java.security.cert.X509Certificate; import java.util.Collections; import java.util.regex.Pattern; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import javax.security.auth.x500.X500Principal; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Matchers.anyList; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class PkiRealmTests extends ESTestCase { - private Settings globalSettings; @Before @@ -40,7 +45,6 @@ public class PkiRealmTests extends ESTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test public void testTokenSupport() { RealmConfig config = new RealmConfig("", Settings.EMPTY, globalSettings); PkiRealm realm = new PkiRealm(config, mock(DnRoleMapper.class)); @@ -50,8 +54,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(realm.supports(new X509AuthenticationToken(new X509Certificate[0], "", "")), is(true)); } - @Test - public void extractTokenFromRestRequest() throws Exception { + public void testExtractTokenFromRestRequest() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); RestRequest restRequest = new FakeRestRequest(); restRequest.putInContext(PkiRealm.PKI_CERT_HEADER_NAME, new X509Certificate[] { certificate }); @@ -63,8 +66,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(token.principal(), is("Elasticsearch Test Node")); } - @Test - public void extractTokenFromTransportMessage() throws Exception { + public void testExtractTokenFromTransportMessage() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); Message message = new Message(); message.putInContext(PkiRealm.PKI_CERT_HEADER_NAME, new X509Certificate[]{certificate}); @@ -76,8 +78,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(token.principal(), is("Elasticsearch Test Node")); } - @Test - public void authenticateBasedOnCertToken() throws Exception { + public void testAuthenticateBasedOnCertToken() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); X509AuthenticationToken token = new X509AuthenticationToken(new X509Certificate[] { certificate }, "Elasticsearch Test Node", "CN=Elasticsearch Test Node,"); DnRoleMapper roleMapper = mock(DnRoleMapper.class); @@ -91,8 +92,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(user.roles().length, is(0)); } - @Test - public void customUsernamePattern() throws Exception { + public void testCustomUsernamePattern() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); DnRoleMapper roleMapper = mock(DnRoleMapper.class); PkiRealm realm = new PkiRealm(new RealmConfig("", Settings.builder().put("username_pattern", "OU=(.*?),").build(), globalSettings), roleMapper); @@ -108,8 +108,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(user.roles().length, is(0)); } - @Test - public void verificationUsingATruststore() throws Exception { + public void testVerificationUsingATruststore() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); DnRoleMapper roleMapper = mock(DnRoleMapper.class); Settings settings = Settings.builder() @@ -130,8 +129,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(user.roles().length, is(0)); } - @Test - public void verificationFailsUsingADifferentTruststore() throws Exception { + public void testVerificationFailsUsingADifferentTruststore() throws Exception { X509Certificate certificate = readCert(getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.cert")); DnRoleMapper roleMapper = mock(DnRoleMapper.class); Settings settings = Settings.builder() @@ -149,8 +147,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(user, is(nullValue())); } - @Test - public void truststorePathWithoutPasswordThrowsException() throws Exception { + public void testTruststorePathWithoutPasswordThrowsException() throws Exception { Settings settings = Settings.builder() .put("truststore.path", getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-client-profile.jks")) .build(); @@ -162,8 +159,7 @@ public class PkiRealmTests extends ESTestCase { } } - @Test - public void certificateWithOnlyCnExtractsProperly() throws Exception { + public void testCertificateWithOnlyCnExtractsProperly() throws Exception { X509Certificate certificate = mock(X509Certificate.class); X500Principal principal = new X500Principal("CN=PKI Client"); when(certificate.getSubjectX500Principal()).thenReturn(principal); @@ -174,8 +170,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(token.dn(), is("CN=PKI Client")); } - @Test - public void certificateWithCnAndOuExtractsProperly() throws Exception { + public void testCertificateWithCnAndOuExtractsProperly() throws Exception { X509Certificate certificate = mock(X509Certificate.class); X500Principal principal = new X500Principal("CN=PKI Client, OU=Shield"); when(certificate.getSubjectX500Principal()).thenReturn(principal); @@ -186,8 +181,7 @@ public class PkiRealmTests extends ESTestCase { assertThat(token.dn(), is("CN=PKI Client, OU=Shield")); } - @Test - public void certificateWithCnInMiddle() throws Exception { + public void testCertificateWithCnInMiddle() throws Exception { X509Certificate certificate = mock(X509Certificate.class); X500Principal principal = new X500Principal("EMAILADDRESS=pki@elastic.co, CN=PKI Client, OU=Shield"); when(certificate.getSubjectX500Principal()).thenReturn(principal); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index 6f44bef7242..b3e32ef0ce5 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -23,29 +23,31 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; + +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Locale; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Locale; import static org.hamcrest.Matchers.is; @ClusterScope(numClientNodes = 0, numDataNodes = 1) public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { - private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + @Override public X509Certificate[] getAcceptedIssuers() { return null; } + @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } + @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } @@ -69,13 +71,11 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { .build(); } - @Test public void testThatTransportClientWorks() { Client client = internalCluster().transportClient(); assertGreenClusterState(client); } - @Test public void testThatHttpWorks() throws Exception { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); SSLContext sc = SSLContext.getInstance("SSL"); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java index 60e671ff534..aaa5c5f5eee 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java @@ -18,13 +18,11 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.Test; import static org.hamcrest.Matchers.is; @ClusterScope(numClientNodes = 0, numDataNodes = 1) public class PkiWithoutSSLTests extends ShieldIntegTestCase { - @Override public boolean sslTransportEnabled() { return false; @@ -40,13 +38,11 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase { .build(); } - @Test public void testThatTransportClientWorks() { Client client = internalCluster().transportClient(); assertGreenClusterState(client); } - @Test public void testThatHttpWorks() throws Exception { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/BCryptTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/BCryptTests.java index 0f5c3d7763c..4a397f7f31a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/BCryptTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/BCryptTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.shield.authc.support; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.ArrayList; import java.util.List; @@ -22,8 +21,6 @@ import static org.hamcrest.Matchers.is; * Tests for the Bcrypt implementation specifically around modifications we have made */ public class BCryptTests extends ESTestCase { - - /* * This test checks that the BCrypt implementation can verify passwords correctly when being invoked from multiple * threads all the time. This attempts to simulate authentication of many clients at once (without a cache). @@ -32,7 +29,6 @@ public class BCryptTests extends ESTestCase { * 100% reliable unless memory parameters are changed such as lowering the heap size to something really small like * 16M and the test is really slow since the issue depends on garbage collection and object finalization. */ - @Test @AwaitsFix(bugUrl = "need a better way to test this") public void testUnderLoad() throws Exception { final String password = randomAsciiOfLengthBetween(10, 32); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/CachingUsernamePasswordRealmTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/CachingUsernamePasswordRealmTests.java index 44fe92c0743..374f95f014c 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/CachingUsernamePasswordRealmTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/CachingUsernamePasswordRealmTests.java @@ -12,14 +12,16 @@ import org.elasticsearch.shield.authc.Realm; import org.elasticsearch.shield.authc.RealmConfig; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; public class CachingUsernamePasswordRealmTests extends ESTestCase { - private Settings globalSettings; @Before @@ -27,9 +29,7 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { globalSettings = Settings.builder().put("path.home", createTempDir()).build(); } - @Test public void testSettings() throws Exception { - String hashAlgo = randomFrom("bcrypt", "bcrypt4", "bcrypt5", "bcrypt6", "bcrypt7", "bcrypt8", "bcrypt9", "sha1", "ssha256", "md5", "clear_text", "noop"); int maxUsers = randomIntBetween(10, 100); TimeValue ttl = TimeValue.timeValueMinutes(randomIntBetween(10, 20)); @@ -60,7 +60,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(realm.hasher, sameInstance(Hasher.resolve(hashAlgo))); } - @Test public void testAuthCache() { AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); SecuredString pass = SecuredStringTests.build("pass"); @@ -77,7 +76,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(realm.lookupInvocationCounter.intValue(), is(0)); } - @Test public void testLookupCache() { AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); realm.lookupUser("a"); @@ -93,7 +91,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(realm.lookupInvocationCounter.intValue(), is(3)); } - @Test public void testLookupAndAuthCache() { AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); // lookup first @@ -121,8 +118,7 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(user, sameInstance(lookedUp)); } - @Test - public void testCache_changePassword(){ + public void testCacheChangePassword(){ AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); String user = "testUser"; @@ -140,7 +136,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(realm.authInvocationCounter.intValue(), is(2)); } - @Test public void testAuthenticateContract() throws Exception { Realm realm = new FailingAuthenticationRealm(Settings.EMPTY, globalSettings); User user = realm.authenticate(new UsernamePasswordToken("user", SecuredStringTests.build("pass"))); @@ -151,7 +146,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(user , nullValue()); } - @Test public void testLookupContract() throws Exception { Realm realm = new FailingAuthenticationRealm(Settings.EMPTY, globalSettings); User user = realm.lookupUser("user"); @@ -162,7 +156,6 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { assertThat(user , nullValue()); } - @Test public void testThatLookupIsNotCalledIfNotSupported() throws Exception { LookupNotSupportedRealm realm = new LookupNotSupportedRealm(globalSettings); assertThat(realm.userLookupSupported(), is(false)); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/HasherTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/HasherTests.java index 7c494a2317a..d914a6bd4ab 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/HasherTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/HasherTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.shield.authc.support; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.hamcrest.Matchers.sameInstance; @@ -14,9 +13,7 @@ import static org.hamcrest.Matchers.sameInstance; * */ public class HasherTests extends ESTestCase { - - @Test - public void testBcryptFamily_SelfGenerated() throws Exception { + public void testBcryptFamilySelfGenerated() throws Exception { testHasherSelfGenerated(Hasher.BCRYPT); testHasherSelfGenerated(Hasher.BCRYPT4); testHasherSelfGenerated(Hasher.BCRYPT5); @@ -26,27 +23,22 @@ public class HasherTests extends ESTestCase { testHasherSelfGenerated(Hasher.BCRYPT9); } - @Test - public void testMd5_SelfGenerated() throws Exception { + public void testMd5SelfGenerated() throws Exception { testHasherSelfGenerated(Hasher.MD5); } - @Test - public void testSha1_SelfGenerated() throws Exception { + public void testSha1SelfGenerated() throws Exception { testHasherSelfGenerated(Hasher.SHA1); } - @Test - public void testSSHA256_SelfGenerated() throws Exception { + public void testSSHA256SelfGenerated() throws Exception { testHasherSelfGenerated(Hasher.SSHA256); } - @Test - public void testNoop_SelfGenerated() throws Exception { + public void testNoopSelfGenerated() throws Exception { testHasherSelfGenerated(Hasher.NOOP); } - @Test public void testResolve() throws Exception { assertThat(Hasher.resolve("bcrypt"), sameInstance(Hasher.BCRYPT)); assertThat(Hasher.resolve("bcrypt4"), sameInstance(Hasher.BCRYPT4)); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/SecuredStringTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/SecuredStringTests.java index bb2a5436c69..e1d3c51ff34 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/SecuredStringTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/SecuredStringTests.java @@ -6,18 +6,18 @@ package org.elasticsearch.shield.authc.support; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.nio.charset.StandardCharsets; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.sameInstance; public class SecuredStringTests extends ESTestCase { public static SecuredString build(String password){ return new SecuredString(password.toCharArray()); } - @Test public void testAccessAfterClear(){ SecuredString password = new SecuredString("password".toCharArray()); SecuredString password2 = new SecuredString("password".toCharArray()); @@ -47,7 +47,6 @@ public class SecuredStringTests extends ESTestCase { assertNotEquals(password, password2); } - @Test public void testEqualsHashCode(){ SecuredString password = new SecuredString("password".toCharArray()); SecuredString password2 = new SecuredString("password".toCharArray()); @@ -56,7 +55,6 @@ public class SecuredStringTests extends ESTestCase { assertEquals(password.hashCode(), password2.hashCode()); } - @Test public void testsEqualsCharSequence(){ SecuredString password = new SecuredString("password".toCharArray()); StringBuffer password2 = new StringBuffer("password"); @@ -66,7 +64,6 @@ public class SecuredStringTests extends ESTestCase { assertEquals(password, password3); } - @Test public void testConcat() { SecuredString password = new SecuredString("password".toCharArray()); SecuredString password2 = new SecuredString("password".toCharArray()); @@ -76,7 +73,6 @@ public class SecuredStringTests extends ESTestCase { assertThat(password3.internalChars(), equalTo("passwordpassword".toCharArray())); } - @Test public void testSubsequence(){ SecuredString password = new SecuredString("password".toCharArray()); SecuredString password2 = password.subSequence(4, 8); @@ -87,7 +83,6 @@ public class SecuredStringTests extends ESTestCase { assertThat("ensure original is unmodified", password.internalChars(), equalTo("password".toCharArray())); } - @Test public void testUFT8(){ String password = "эластичный поиск-弾性検索"; SecuredString securePass = new SecuredString(password.toCharArray()); @@ -96,7 +91,6 @@ public class SecuredStringTests extends ESTestCase { assertThat(password2, equalTo(password)); } - @Test public void testCopyChars() throws Exception { String password = "эластичный поиск-弾性検索"; SecuredString securePass = new SecuredString(password.toCharArray()); diff --git a/shield/src/test/java/org/elasticsearch/shield/authc/support/UsernamePasswordTokenTests.java b/shield/src/test/java/org/elasticsearch/shield/authc/support/UsernamePasswordTokenTests.java index cdcb9b74368..fcab37e1f9d 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authc/support/UsernamePasswordTokenTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authc/support/UsernamePasswordTokenTests.java @@ -11,13 +11,15 @@ import org.elasticsearch.rest.RestRequest; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportRequest; import org.junit.Rule; -import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -25,11 +27,9 @@ import static org.mockito.Mockito.when; * */ public class UsernamePasswordTokenTests extends ESTestCase { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Test public void testPutToken() throws Exception { TransportRequest request = new TransportRequest() {}; UsernamePasswordToken.putTokenHeader(request, new UsernamePasswordToken("user1", SecuredStringTests.build("test123"))); @@ -46,7 +46,6 @@ public class UsernamePasswordTokenTests extends ESTestCase { assertThat(password, equalTo("test123")); } - @Test public void testExtractToken() throws Exception { TransportRequest request = new TransportRequest() {}; String header = "Basic " + Base64.encodeBytes("user1:test123".getBytes(StandardCharsets.UTF_8)); @@ -57,8 +56,7 @@ public class UsernamePasswordTokenTests extends ESTestCase { assertThat(new String(token.credentials().internalChars()), equalTo("test123")); } - @Test - public void testExtractToken_Invalid() throws Exception { + public void testExtractTokenInvalid() throws Exception { String[] invalidValues = { "Basic", "Basic ", "Basic f" }; for (String value : invalidValues) { TransportRequest request = new TransportRequest() {}; @@ -73,7 +71,6 @@ public class UsernamePasswordTokenTests extends ESTestCase { } } - @Test public void testThatAuthenticationExceptionContainsResponseHeaders() { TransportRequest request = new TransportRequest() {}; String header = "BasicBroken"; @@ -86,7 +83,6 @@ public class UsernamePasswordTokenTests extends ESTestCase { } } - @Test public void testExtractTokenRest() throws Exception { RestRequest request = mock(RestRequest.class); UsernamePasswordToken token = new UsernamePasswordToken("username", SecuredStringTests.build("changeme")); @@ -94,44 +90,38 @@ public class UsernamePasswordTokenTests extends ESTestCase { assertThat(UsernamePasswordToken.extractToken(request, null), equalTo(token)); } - @Test - public void testExtractTokenRest_Missing() throws Exception { + public void testExtractTokenRestMissing() throws Exception { RestRequest request = mock(RestRequest.class); when(request.header(UsernamePasswordToken.BASIC_AUTH_HEADER)).thenReturn(null); assertThat(UsernamePasswordToken.extractToken(request, null), nullValue()); } - @Test - public void testExtractTokenRest_WithInvalidToken1() throws Exception { + public void testExtractTokenRestWithInvalidToken1() throws Exception { thrown.expect(ElasticsearchSecurityException.class); RestRequest request = mock(RestRequest.class); when(request.header(UsernamePasswordToken.BASIC_AUTH_HEADER)).thenReturn("invalid"); UsernamePasswordToken.extractToken(request, null); } - @Test - public void testExtractTokenRest_WithInvalidToken2() throws Exception { + public void testExtractTokenRestWithInvalidToken2() throws Exception { thrown.expect(ElasticsearchSecurityException.class); RestRequest request = mock(RestRequest.class); when(request.header(UsernamePasswordToken.BASIC_AUTH_HEADER)).thenReturn("Basic"); UsernamePasswordToken.extractToken(request, null); } - @Test public void testEqualsWithDifferentPasswords() { UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecuredString("new password".toCharArray())); assertThat(token1, not(equalTo(token2))); } - @Test public void testEqualsWithDifferentUsernames() { UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); UsernamePasswordToken token2 = new UsernamePasswordToken("username1", new SecuredString("password".toCharArray())); assertThat(token1, not(equalTo(token2))); } - @Test public void testEquals() { UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/AnalyzeTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/AnalyzeTests.java index 2b6f2f27c14..e684ff9ffce 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/AnalyzeTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/AnalyzeTests.java @@ -9,7 +9,6 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.shield.authc.support.Hasher; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; @@ -17,7 +16,6 @@ import static org.elasticsearch.test.ShieldTestsUtils.assertAuthorizationExcepti import static org.hamcrest.CoreMatchers.containsString; public class AnalyzeTests extends ShieldIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("test123".toCharArray()))); @Override @@ -46,7 +44,6 @@ public class AnalyzeTests extends ShieldIntegTestCase { " - cluster:admin/analyze\n"; } - @Test public void testAnalyzeWithIndices() { //this test tries to execute different analyze api variants from a user that has analyze privileges only on a specific index namespace @@ -74,7 +71,6 @@ public class AnalyzeTests extends ShieldIntegTestCase { } } - @Test public void testAnalyzeWithoutIndices() { //this test tries to execute different analyze api variants from a user that has analyze privileges only at cluster level diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/IndexAliasesTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/IndexAliasesTests.java index 79e7f5de9f5..0986c9c1615 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/IndexAliasesTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/IndexAliasesTests.java @@ -15,13 +15,14 @@ import org.elasticsearch.shield.authc.support.Hasher; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.ShieldIntegTestCase; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthorizationException; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; -import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; public class IndexAliasesTests extends ShieldIntegTestCase { @@ -82,7 +83,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexThenAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to add/remove aliases assertAcked(client().admin().indices().prepareCreate("test_1") @@ -105,7 +105,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexAndAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to add aliases although they are part of the same create index request try { @@ -117,7 +116,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testDeleteAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to add/remove aliases try { @@ -145,7 +143,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testGetAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to retrieve aliases though try { @@ -189,7 +186,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexThenAliasesCreateAndAliasesPermission() { //user has create and manage_aliases permission on test_*. manage_aliases is required to add/remove aliases on both aliases and indices assertAcked(client().admin().indices().prepareCreate("test_1") @@ -213,7 +209,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexAndAliasesCreateAndAliasesPermission() { //user has create and manage_aliases permission on test_*. manage_aliases is required to add/remove aliases on both aliases and indices //ok: user has manage_aliases on test_* @@ -230,7 +225,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testDeleteAliasesCreateAndAliasesPermission() { //user has create and manage_aliases permission on test_*. manage_aliases is required to add/remove aliases on both aliases and indices //ok: user has manage_aliases on test_* @@ -284,7 +278,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testGetAliasesCreateAndAliasesPermission() { //user has create and manage_aliases permission on test_*. manage_aliases is required to retrieve aliases on both aliases and indices @@ -350,7 +343,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexThenAliasesCreateAndAliasesPermission2() { //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases on both aliases and indices assertAcked(client().admin().indices().prepareCreate("test_1") @@ -384,7 +376,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexAndAliasesCreateAndAliasesPermission2() { //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases on both aliases and indices try { @@ -406,7 +397,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testDeleteAliasesCreateAndAliasesPermission2() { //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases on both aliases and indices try { @@ -437,7 +427,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testGetAliasesCreateAndAliasesPermission2() { //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to retrieve aliases on both aliases and indices assertAcked(client().admin().indices().prepareCreate("test_1") @@ -507,7 +496,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testCreateIndexThenAliasesCreateAndAliasesPermission3() { //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. assertAcked(client().admin().indices().prepareCreate("test_1") @@ -523,7 +511,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { .putHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray())))); } - @Test public void testCreateIndexAndAliasesCreateAndAliasesPermission3() { //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. assertAcked(client().admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias")) @@ -533,7 +520,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { .putHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray())))); } - @Test public void testDeleteAliasesCreateAndAliasesPermission3() { //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. assertAcked(client().admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias")).addAlias(new Alias("alias_1")) @@ -566,7 +552,6 @@ public class IndexAliasesTests extends ShieldIntegTestCase { } } - @Test public void testGetAliasesCreateAndAliasesPermission3() { //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. assertAcked(client().admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias")).addAlias(new Alias("alias_1")) @@ -609,13 +594,16 @@ public class IndexAliasesTests extends ShieldIntegTestCase { "test_1", "alias_1"); } - @Test(expected = ElasticsearchSecurityException.class) public void testCreateIndexAliasesOnlyPermission() { - client().admin().indices().prepareCreate("test_1") - .putHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue("aliases_only", new SecuredString("test123".toCharArray()))).get(); + try { + client().admin().indices().prepareCreate("test_1") + .putHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue("aliases_only", new SecuredString("test123".toCharArray()))).get(); + fail("Expected ElasticsearchSecurityException"); + } catch (ElasticsearchSecurityException e) { + assertThat(e.getMessage(), is("action [indices:admin/create] is unauthorized for user [aliases_only]")); + } } - @Test public void testGetAliasesAliasesOnlyPermission() { //user has manage_aliases only permissions on both alias_* and test_* diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/InternalAuthorizationServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/InternalAuthorizationServiceTests.java index a5ed6fabf3a..258815e555e 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/InternalAuthorizationServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/InternalAuthorizationServiceTests.java @@ -12,7 +12,11 @@ import org.elasticsearch.action.admin.indices.alias.IndicesAliasesAction; import org.elasticsearch.action.admin.indices.create.CreateIndexAction; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; -import org.elasticsearch.action.search.*; +import org.elasticsearch.action.search.ClearScrollAction; +import org.elasticsearch.action.search.ClearScrollRequest; +import org.elasticsearch.action.search.SearchAction; +import org.elasticsearch.action.search.SearchScrollAction; +import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.AliasMetaData; @@ -28,17 +32,22 @@ import org.elasticsearch.shield.authz.store.RolesStore; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportRequest; import org.junit.Before; -import org.junit.Test; import java.util.List; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthorizationException; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; public class InternalAuthorizationServiceTests extends ESTestCase { - private AuditTrail auditTrail; private RolesStore rolesStore; private ClusterService clusterService; @@ -53,7 +62,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { internalAuthorizationService = new InternalAuthorizationService(Settings.EMPTY, rolesStore, clusterService, auditTrail, anonymousService, new DefaultAuthenticationFailureHandler()); } - @Test public void testActionsSystemUserIsAuthorized() { TransportRequest request = mock(TransportRequest.class); @@ -66,7 +74,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { verifyNoMoreInteractions(auditTrail); } - @Test public void testIndicesActionsAreNotAuthorized() { TransportRequest request = mock(TransportRequest.class); try { @@ -79,7 +86,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testClusterAdminActionsAreNotAuthorized() { TransportRequest request = mock(TransportRequest.class); try { @@ -92,7 +98,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testClusterAdminSnapshotStatusActionIsNotAuthorized() { TransportRequest request = mock(TransportRequest.class); try { @@ -105,7 +110,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testNoRolesCausesDenial() { TransportRequest request = mock(TransportRequest.class); User user = new User.Simple("test user", null); @@ -119,7 +123,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testUnknownRoleCausesDenial() { TransportRequest request = mock(TransportRequest.class); User user = new User.Simple("test user", new String[] { "non-existent-role" }); @@ -133,7 +136,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testThatNonIndicesAndNonClusterActionIsDenied() { TransportRequest request = mock(TransportRequest.class); User user = new User.Simple("test user", new String[] { "a_all" }); @@ -149,7 +151,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testThatRoleWithNoIndicesIsDenied() { TransportRequest request = new IndicesExistsRequest("a"); User user = new User.Simple("test user", new String[] { "no_indices" }); @@ -165,7 +166,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testScrollRelatedRequestsAllowed() { User user = new User.Simple("test user", new String[] { "a_all" }); when(rolesStore.role("a_all")).thenReturn(Permission.Global.Role.builder("a_role").add(Privilege.Index.ALL, "a").build()); @@ -197,7 +197,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { verifyNoMoreInteractions(auditTrail); } - @Test public void testAuthorizeIndicesFailures() { TransportRequest request = new IndicesExistsRequest("b"); ClusterState state = mock(ClusterState.class); @@ -218,7 +217,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testCreateIndexWithAliasWithoutPermissions() { CreateIndexRequest request = new CreateIndexRequest("a"); request.alias(new Alias("a2")); @@ -240,7 +238,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testCreateIndexWithAlias() { CreateIndexRequest request = new CreateIndexRequest("a"); request.alias(new Alias("a2")); @@ -258,7 +255,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { verify(state, times(2)).metaData(); } - @Test public void testIndicesAliasesWithNoRolesUser() { User user = new User.Simple("test user", null); @@ -266,7 +262,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { assertThat(list.isEmpty(), is(true)); } - @Test public void testIndicesAliasesWithUserHavingRoles() { User user = new User.Simple("test user", new String[] { "a_star", "b" }); ClusterState state = mock(ClusterState.class); @@ -294,7 +289,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { assertThat(list.contains("ba"), is(false)); } - @Test public void testDenialForAnonymousUser() { TransportRequest request = new IndicesExistsRequest("b"); ClusterState state = mock(ClusterState.class); @@ -317,7 +311,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testDenialForAnonymousUserAuthorizationExceptionDisabled() { TransportRequest request = new IndicesExistsRequest("b"); ClusterState state = mock(ClusterState.class); @@ -343,7 +336,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testRunAsRequestWithNoRolesUser() { TransportRequest request = mock(TransportRequest.class); User user = new User.Simple("test user", null, new User.Simple("run as me", new String[] { "admin" })); @@ -358,7 +350,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testRunAsRequestRunningAsUnAllowedUser() { TransportRequest request = mock(TransportRequest.class); User user = new User.Simple("test user", new String[] { "can run as" }, new User.Simple("run as me", new String[] { "doesn't exist" })); @@ -379,7 +370,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testRunAsRequestWithRunAsUserWithoutPermission() { TransportRequest request = new IndicesExistsRequest("a"); User user = new User.Simple("test user", new String[] { "can run as" }, new User.Simple("run as me", new String[] { "b" })); @@ -415,7 +405,6 @@ public class InternalAuthorizationServiceTests extends ESTestCase { } } - @Test public void testRunAsRequestWithValidPermissions() { TransportRequest request = new IndicesExistsRequest("b"); User user = new User.Simple("test user", new String[] { "can run as" }, new User.Simple("run as me", new String[] { "b" })); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/PermissionTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/PermissionTests.java index cd5e7bdf8ec..3c8d6db0ff4 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/PermissionTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/PermissionTests.java @@ -6,16 +6,15 @@ package org.elasticsearch.shield.authz; import org.elasticsearch.action.get.GetAction; +import org.elasticsearch.shield.authz.Privilege.Cluster; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.function.Predicate; -import static org.elasticsearch.shield.authz.Privilege.Index.Cluster; import static org.elasticsearch.shield.authz.Privilege.Index.MONITOR; import static org.elasticsearch.shield.authz.Privilege.Index.READ; import static org.elasticsearch.shield.authz.Privilege.Index.SEARCH; @@ -28,7 +27,6 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class PermissionTests extends ESTestCase { - private Permission.Global.Role permission; @Before @@ -40,19 +38,16 @@ public class PermissionTests extends ESTestCase { permission = builder.build(); } - @Test - public void testAllowedIndicesMatcher_Action() throws Exception { + public void testAllowedIndicesMatcherAction() throws Exception { testAllowedIndicesMatcher(permission.indices().allowedIndicesMatcher(GetAction.NAME)); } - @Test - public void testAllowedIndicesMatcher_Action_Caching() throws Exception { + public void testAllowedIndicesMatcherActionCaching() throws Exception { Predicate matcher1 = permission.indices().allowedIndicesMatcher(GetAction.NAME); Predicate matcher2 = permission.indices().allowedIndicesMatcher(GetAction.NAME); assertThat(matcher1, is(matcher2)); } - @Test public void testIndicesGlobalsIterator() { Permission.Global.Role.Builder builder = Permission.Global.Role.builder("tc_role"); builder.cluster(Cluster.action("cluster:monitor/nodes/info")); @@ -69,8 +64,7 @@ public class PermissionTests extends ESTestCase { assertThat(count, is(equalTo(permission.indices().groups().length))); } - @Test - public void buildEmptyRole() { + public void testBuildEmptyRole() { Permission.Global.Role.Builder permission = Permission.Global.Role.builder("some_role"); Permission.Global.Role role = permission.build(); assertThat(role, notNullValue()); @@ -79,7 +73,6 @@ public class PermissionTests extends ESTestCase { assertThat(role.runAs(), notNullValue()); } - @Test public void testRunAs() { Permission.Global.Role permission = Permission.Global.Role.builder("some_role") .runAs(new Privilege.General("name", "user1", "run*")) diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/PrivilegeTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/PrivilegeTests.java index fb2091afb6c..d35963ae316 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/PrivilegeTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/PrivilegeTests.java @@ -14,11 +14,11 @@ import org.elasticsearch.shield.support.AutomatonPredicate; import org.elasticsearch.shield.support.Automatons; import org.elasticsearch.test.ESTestCase; import org.junit.Rule; -import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.function.Predicate; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -27,11 +27,9 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class PrivilegeTests extends ESTestCase { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Test public void testName() throws Exception { Privilege.Name name12 = new Privilege.Name("name1", "name2"); Privilege.Name name34 = new Privilege.Name("name3", "name4"); @@ -48,7 +46,6 @@ public class PrivilegeTests extends ESTestCase { assertThat(none, is(Privilege.Name.NONE)); } - @Test public void testSubActionPattern() throws Exception { AutomatonPredicate predicate = new AutomatonPredicate(Automatons.patterns("foo" + Privilege.SUB_ACTION_SUFFIX_PATTERN)); assertThat(predicate.test("foo[n][nodes]"), is(true)); @@ -57,9 +54,7 @@ public class PrivilegeTests extends ESTestCase { assertThat(predicate.test("[n][nodes]"), is(false)); } - @Test public void testCluster() throws Exception { - Privilege.Name name = new Privilege.Name("monitor"); Privilege.Cluster cluster = Privilege.Cluster.get(name); assertThat(cluster, is(Privilege.Cluster.MONITOR)); @@ -78,9 +73,7 @@ public class PrivilegeTests extends ESTestCase { assertThat(cluster, is(cluster2)); } - @Test - public void testCluster_TemplateActions() throws Exception { - + public void testClusterTemplateActions() throws Exception { Privilege.Name name = new Privilege.Name("indices:admin/template/delete"); Privilege.Cluster cluster = Privilege.Cluster.get(name); assertThat(cluster, notNullValue()); @@ -97,14 +90,12 @@ public class PrivilegeTests extends ESTestCase { assertThat(cluster.predicate().test("indices:admin/template/put"), is(true)); } - @Test - public void testCluster_InvalidName() throws Exception { + public void testClusterInvalidName() throws Exception { thrown.expect(IllegalArgumentException.class); Privilege.Name actionName = new Privilege.Name("foobar"); Privilege.Cluster.get(actionName); } - @Test public void testClusterAction() throws Exception { Privilege.Name actionName = new Privilege.Name("cluster:admin/snapshot/delete"); Privilege.Cluster cluster = Privilege.Cluster.get(actionName); @@ -113,8 +104,7 @@ public class PrivilegeTests extends ESTestCase { assertThat(cluster.predicate().test("cluster:admin/snapshot/dele"), is(false)); } - @Test - public void testCluster_AddCustom() throws Exception { + public void testClusterAddCustom() throws Exception { Privilege.Cluster.addCustom("foo", "cluster:bar"); boolean found = false; for (Privilege.Cluster cluster : Privilege.Cluster.values()) { @@ -130,17 +120,26 @@ public class PrivilegeTests extends ESTestCase { assertThat(cluster.predicate().test("cluster:bar"), is(true)); } - @Test(expected = IllegalArgumentException.class) - public void testCluster_AddCustom_InvalidPattern() throws Exception { - Privilege.Cluster.addCustom("foo", "bar"); + public void testClusterAddCustomInvalidPattern() throws Exception { + try { + Privilege.Cluster.addCustom("foo", "bar"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("cannot register custom cluster privilege [foo]")); + assertThat(e.getMessage(), containsString("must follow the 'cluster:*' format")); + } } - @Test(expected = IllegalArgumentException.class) - public void testCluster_AddCustom_AlreadyExists() throws Exception { - Privilege.Cluster.addCustom("all", "bar"); + public void testClusterAddCustomAlreadyExists() throws Exception { + try { + Privilege.Cluster.addCustom("all", "bar"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("cannot register custom cluster privilege [all]")); + assertThat(e.getMessage(), containsString("must follow the 'cluster:*' format")); + } } - @Test public void testIndexAction() throws Exception { Privilege.Name actionName = new Privilege.Name("indices:admin/mapping/delete"); Privilege.Index index = Privilege.Index.get(actionName); @@ -149,8 +148,7 @@ public class PrivilegeTests extends ESTestCase { assertThat(index.predicate().test("indices:admin/mapping/dele"), is(false)); } - @Test - public void testIndex_Collapse() throws Exception { + public void testIndexCollapse() throws Exception { Privilege.Index[] values = Privilege.Index.values().toArray(new Privilege.Index[Privilege.Index.values().size()]); Privilege.Index first = values[randomIntBetween(0, values.length-1)]; Privilege.Index second = values[randomIntBetween(0, values.length-1)]; @@ -167,8 +165,7 @@ public class PrivilegeTests extends ESTestCase { } } - @Test - public void testIndex_Implies() throws Exception { + public void testIndexImplies() throws Exception { Privilege.Index[] values = Privilege.Index.values().toArray(new Privilege.Index[Privilege.Index.values().size()]); Privilege.Index first = values[randomIntBetween(0, values.length-1)]; Privilege.Index second = values[randomIntBetween(0, values.length-1)]; @@ -200,8 +197,7 @@ public class PrivilegeTests extends ESTestCase { } } - @Test - public void testIndex_AddCustom() throws Exception { + public void testIndexAddCustom() throws Exception { Privilege.Index.addCustom("foo", "indices:bar"); boolean found = false; for (Privilege.Index index : Privilege.Index.values()) { @@ -217,17 +213,26 @@ public class PrivilegeTests extends ESTestCase { assertThat(index.predicate().test("indices:bar"), is(true)); } - @Test(expected = IllegalArgumentException.class) - public void testIndex_AddCustom_InvalidPattern() throws Exception { - Privilege.Index.addCustom("foo", "bar"); + public void testIndexAddCustomInvalidPattern() throws Exception { + try { + Privilege.Index.addCustom("foo", "bar"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("cannot register custom index privilege [foo]")); + assertThat(e.getMessage(), containsString("must follow the 'indices:*' format")); + } } - @Test(expected = IllegalArgumentException.class) - public void testIndex_AddCustom_AlreadyExists() throws Exception { - Privilege.Index.addCustom("all", "bar"); + public void testIndexAddCustomAlreadyExists() throws Exception { + try { + Privilege.Index.addCustom("all", "bar"); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("cannot register custom index privilege [all]")); + assertThat(e.getMessage(), containsString("must follow the 'indices:*' format")); + } } - @Test public void testSystem() throws Exception { Predicate predicate = Privilege.SYSTEM.predicate(); assertThat(predicate.test("indices:monitor/whatever"), is(true)); @@ -244,7 +249,6 @@ public class PrivilegeTests extends ESTestCase { assertThat(predicate.test("indices:admin/mapping/whatever"), is(false)); } - @Test public void testSearchPrivilege() throws Exception { Predicate predicate = Privilege.Index.SEARCH.predicate(); assertThat(predicate.test(SearchAction.NAME), is(true)); @@ -260,7 +264,6 @@ public class PrivilegeTests extends ESTestCase { assertThat(predicate.test(MultiGetAction.NAME + "/whatever"), is(false)); } - @Test public void testGetPrivilege() throws Exception { Predicate predicate = Privilege.Index.GET.predicate(); assertThat(predicate.test(GetAction.NAME), is(true)); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/SystemRoleTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/SystemRoleTests.java index b48f02fe5f9..276e7dd71c9 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/SystemRoleTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/SystemRoleTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.shield.authz; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.hamcrest.Matchers.is; @@ -14,8 +13,6 @@ import static org.hamcrest.Matchers.is; * */ public class SystemRoleTests extends ESTestCase { - - @Test public void testCheck() throws Exception { assertThat(SystemRole.INSTANCE.check("indices:monitor/whatever"), is(true)); assertThat(SystemRole.INSTANCE.check("cluster:monitor/whatever"), is(true)); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/DefaultIndicesResolverTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/DefaultIndicesResolverTests.java index 6d08310f66f..3293687c98d 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/DefaultIndicesResolverTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/DefaultIndicesResolverTests.java @@ -30,18 +30,19 @@ import org.elasticsearch.shield.User; import org.elasticsearch.shield.authz.AuthorizationService; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Set; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultIndicesResolverTests extends ESTestCase { - private User user; private User userNoIndices; private MetaData metaData; @@ -86,7 +87,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { defaultIndicesResolver = new DefaultIndicesAndAliasesResolver(authzService); } - @Test public void testResolveEmptyIndicesExpandWilcardsOpenAndClosed() { SearchRequest request = new SearchRequest(); request.indicesOptions(IndicesOptions.strictExpand()); @@ -97,7 +97,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveEmptyIndicesExpandWilcardsOpen() { SearchRequest request = new SearchRequest(); request.indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -108,7 +107,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveAllExpandWilcardsOpenAndClosed() { SearchRequest request = new SearchRequest("_all"); request.indicesOptions(IndicesOptions.strictExpand()); @@ -119,7 +117,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveAllExpandWilcardsOpen() { SearchRequest request = new SearchRequest("_all"); request.indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -130,7 +127,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsExpandWilcardsOpenAndClosed() { SearchRequest request = new SearchRequest("barbaz", "foofoo*"); request.indicesOptions(IndicesOptions.strictExpand()); @@ -141,7 +137,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsExpandWilcardsOpen() { SearchRequest request = new SearchRequest("barbaz", "foofoo*"); request.indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -152,7 +147,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsMinusExpandWilcardsOpen() { SearchRequest request = new SearchRequest("-foofoo*"); request.indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -163,7 +157,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsMinusExpandWilcardsOpenAndClosed() { SearchRequest request = new SearchRequest("-foofoo*"); request.indicesOptions(IndicesOptions.strictExpand()); @@ -174,7 +167,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsPlusAndMinusExpandWilcardsOpen() { SearchRequest request = new SearchRequest("-foofoo*", "+barbaz", "+foob*"); request.indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -185,7 +177,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test public void testResolveWildcardsPlusAndMinusExpandWilcardsOpenAndClosed() { SearchRequest request = new SearchRequest("-foofoo*", "+barbaz"); request.indicesOptions(IndicesOptions.strictExpand()); @@ -196,19 +187,26 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), arrayContaining(replacedIndices)); } - @Test(expected = IndexNotFoundException.class) public void testResolveNonMatchingIndices() { SearchRequest request = new SearchRequest("missing*"); - defaultIndicesResolver.resolve(user, SearchAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, SearchAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testResolveNoAuthorizedIndices() { SearchRequest request = new SearchRequest(); - defaultIndicesResolver.resolve(userNoIndices, SearchAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, SearchAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveMissingIndex() { SearchRequest request = new SearchRequest("bar*", "missing"); Set indices = defaultIndicesResolver.resolve(user, SearchAction.NAME, request, metaData); @@ -218,7 +216,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), equalTo(expectedIndices)); } - @Test public void testResolveNonMatchingIndicesAndExplicit() { SearchRequest request = new SearchRequest("missing*", "bar"); Set indices = defaultIndicesResolver.resolve(user, SearchAction.NAME, request, metaData); @@ -227,7 +224,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), equalTo(expectedIndices)); } - @Test public void testResolveNoExpand() { SearchRequest request = new SearchRequest("missing*"); request.indicesOptions(IndicesOptions.strictSingleIndexNoExpandForbidClosed()); @@ -237,7 +233,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.indices(), equalTo(expectedIndices)); } - @Test public void testResolveIndicesAliasesRequest() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo", "foofoo"); @@ -253,7 +248,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("alias2")); } - @Test public void testResolveIndicesAliasesRequestExistingAlias() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo", "foofoo"); @@ -269,7 +263,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("foofoobar")); } - @Test public void testResolveIndicesAliasesRequestMissingIndex() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo", "foofoo"); @@ -285,7 +278,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("alias2")); } - @Test public void testResolveWildcardsIndicesAliasesRequest() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo*"); @@ -302,17 +294,20 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("alias2")); } - @Test(expected = IndexNotFoundException.class) public void testResolveWildcardsIndicesAliasesRequestNoMatchingIndices() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo*"); request.addAlias("alias2", "bar*"); request.addAlias("alias3", "non_matching_*"); //if a single operation contains wildcards and ends up being resolved to no indices, it makes the whole request fail - defaultIndicesResolver.resolve(user, IndicesAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, IndicesAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveAllIndicesAliasesRequest() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "_all"); @@ -330,23 +325,30 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("alias2")); } - @Test(expected = IndexNotFoundException.class) public void testResolveAllIndicesAliasesRequestNoAuthorizedIndices() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "_all"); //current user is not authorized for any index, _all resolves to no indices, the request fails - defaultIndicesResolver.resolve(userNoIndices, IndicesAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, IndicesAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testResolveWildcardsIndicesAliasesRequestNoAuthorizedIndices() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAlias("alias1", "foo*"); //current user is not authorized for any index, foo* resolves to no indices, the request fails - defaultIndicesResolver.resolve(userNoIndices, IndicesAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, IndicesAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveIndicesAliasesRequestDeleteActions() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("foo", "foofoobar")); @@ -362,7 +364,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("barbaz")); } - @Test public void testResolveIndicesAliasesRequestDeleteActionsMissingIndex() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("foo", "foofoobar")); @@ -378,7 +379,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("missing_alias")); } - @Test public void testResolveWildcardsIndicesAliasesRequestDeleteActions() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("foo*", "foofoobar")); @@ -395,7 +395,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("barbaz")); } - @Test public void testResolveAliasesWildcardsIndicesAliasesRequestDeleteActions() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("*", "foo*")); @@ -414,7 +413,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("foofoobar")); } - @Test public void testResolveAllAliasesWildcardsIndicesAliasesRequestDeleteActions() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("*", "_all")); @@ -433,16 +431,19 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("foofoobar", "explicit")); } - @Test(expected = IndexNotFoundException.class) public void testResolveAliasesWildcardsIndicesAliasesRequestDeleteActionsNoAuthorizedIndices() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("foo*", "foo*")); //no authorized aliases match bar*, hence this action fails and makes the whole request fail request.addAliasAction(AliasAction.newRemoveAliasAction("*bar", "bar*")); - defaultIndicesResolver.resolve(user, IndicesAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, IndicesAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveWildcardsIndicesAliasesRequestAddAndDeleteActions() { IndicesAliasesRequest request = new IndicesAliasesRequest(); request.addAliasAction(AliasAction.newRemoveAliasAction("foo*", "foofoobar")); @@ -459,7 +460,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.getAliasActions().get(1).aliases(), arrayContaining("foofoobar")); } - @Test public void testResolveGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest("alias1").indices("foo", "foofoo"); Set indices = defaultIndicesResolver.resolve(user, GetAliasesAction.NAME, request, metaData); @@ -471,7 +471,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("alias1")); } - @Test public void testResolveGetAliasesRequestMissingIndex() { GetAliasesRequest request = new GetAliasesRequest(); request.indices("missing"); @@ -485,7 +484,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("alias2")); } - @Test public void testResolveWildcardsGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(); request.aliases("alias1"); @@ -500,16 +498,19 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("alias1")); } - @Test(expected = IndexNotFoundException.class) public void testResolveWildcardsGetAliasesRequestNoMatchingIndices() { GetAliasesRequest request = new GetAliasesRequest(); request.aliases("alias3"); request.indices("non_matching_*"); //indices get resolved to no indices, request gets rejected - defaultIndicesResolver.resolve(user, GetAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, GetAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveAllGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(); //even if not set, empty means _all @@ -528,7 +529,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("alias1")); } - @Test public void testResolveAllGetAliasesRequestExpandWildcardsClosed() { GetAliasesRequest request = new GetAliasesRequest(); //set indices options to have wildcards resolved to open and closed indices (default is open only) @@ -549,25 +549,32 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("alias1")); } - @Test(expected = IndexNotFoundException.class) public void testResolveAllGetAliasesRequestNoAuthorizedIndices() { GetAliasesRequest request = new GetAliasesRequest(); request.aliases("alias1"); request.indices("_all"); //current user is not authorized for any index, _all resolves to no indices, the request fails - defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testResolveWildcardsGetAliasesRequestNoAuthorizedIndices() { GetAliasesRequest request = new GetAliasesRequest(); request.aliases("alias1"); request.indices("foo*"); //current user is not authorized for any index, foo* resolves to no indices, the request fails - defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testResolveAllAliasesGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(); if (randomBoolean()) { @@ -586,7 +593,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("foofoobar")); } - @Test public void testResolveAllAndExplicitAliasesGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(new String[]{"_all", "explicit"}); if (randomBoolean()) { @@ -602,7 +608,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("foofoobar", "explicit")); } - @Test public void testResolveAllAndWildcardsAliasesGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(new String[]{"_all", "foo*", "non_matching_*"}); if (randomBoolean()) { @@ -618,7 +623,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("foofoobar", "foofoobar")); } - @Test public void testResolveAliasesWildcardsGetAliasesRequest() { GetAliasesRequest request = new GetAliasesRequest(); request.indices("*bar"); @@ -635,16 +639,19 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.aliases(), arrayContaining("foofoobar")); } - @Test(expected = IndexNotFoundException.class) public void testResolveAliasesWildcardsGetAliasesRequestNoAuthorizedIndices() { GetAliasesRequest request = new GetAliasesRequest(); //no authorized aliases match bar*, hence the request fails request.aliases("bar*"); request.indices("*bar"); - defaultIndicesResolver.resolve(user, GetAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, GetAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testResolveAliasesAllGetAliasesRequestNoAuthorizedIndices() { GetAliasesRequest request = new GetAliasesRequest(); if (randomBoolean()) { @@ -652,11 +659,15 @@ public class DefaultIndicesResolverTests extends ESTestCase { } request.indices("non_existing"); //current user is not authorized for any index, foo* resolves to no indices, the request fails - defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, GetAliasesAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } //msearch is a CompositeIndicesRequest whose items (SearchRequests) implement IndicesRequest.Replaceable, wildcards will get replaced - @Test public void testResolveMultiSearchNoWildcards() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("foo", "bar")); @@ -669,7 +680,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"bar2"})); } - @Test public void testResolveMultiSearchNoWildcardsMissingIndex() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("foo", "bar")); @@ -684,7 +694,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(2).indices(), equalTo(new String[]{"missing"})); } - @Test public void testResolveMultiSearchWildcardsExpandOpen() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("bar*")).indicesOptions(randomFrom(IndicesOptions.strictExpandOpen(), IndicesOptions.lenientExpandOpen())); @@ -697,7 +706,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"foobar"})); } - @Test public void testResolveMultiSearchWildcardsExpandOpenAndClose() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("bar*").indicesOptions(IndicesOptions.strictExpand())); @@ -710,7 +718,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"foobar"})); } - @Test public void testResolveMultiSearchWildcardsMissingIndex() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("bar*")); @@ -723,24 +730,31 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"missing"})); } - @Test(expected = IndexNotFoundException.class) public void testResolveMultiSearchWildcardsNoMatchingIndices() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("missing*")); request.add(Requests.searchRequest("foobar")); - defaultIndicesResolver.resolve(user, MultiSearchAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(user, MultiSearchAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testResolveMultiSearchWildcardsNoAuthorizedIndices() { MultiSearchRequest request = new MultiSearchRequest(); request.add(Requests.searchRequest("foofoo*")); request.add(Requests.searchRequest("foobar")); - defaultIndicesResolver.resolve(userNoIndices, MultiSearchAction.NAME, request, metaData); + try { + defaultIndicesResolver.resolve(userNoIndices, MultiSearchAction.NAME, request, metaData); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } //mget is a CompositeIndicesRequest whose items don't support expanding wildcards - @Test public void testResolveMultiGet() { MultiGetRequest request = new MultiGetRequest(); request.add("foo", "type", "id"); @@ -753,7 +767,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"bar"})); } - @Test public void testResolveMultiGetMissingIndex() { MultiGetRequest request = new MultiGetRequest(); request.add("foo", "type", "id"); @@ -766,7 +779,6 @@ public class DefaultIndicesResolverTests extends ESTestCase { assertThat(request.subRequests().get(1).indices(), equalTo(new String[]{"missing"})); } - @Test public void testResolveAdminAction() { DeleteIndexRequest request = new DeleteIndexRequest("*"); Set indices = defaultIndicesResolver.resolve(user, DeleteIndexAction.NAME, request, metaData); diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/IndicesAndAliasesResolverIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/IndicesAndAliasesResolverIntegrationTests.java index 0cda3f9cbee..69b01b9621c 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/IndicesAndAliasesResolverIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/indicesresolver/IndicesAndAliasesResolverIntegrationTests.java @@ -16,16 +16,17 @@ import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.elasticsearch.test.ShieldTestsUtils.assertAuthorizationException; -import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCase { - @Override protected String configRoles() { return ShieldSettingsSource.DEFAULT_ROLE + ":\n" + @@ -35,7 +36,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa " '/test.*/': read\n"; } - @Test public void testSearchForAll() { //index1 is not authorized and referred to through wildcard createIndices("test1", "test2", "test3", "index1"); @@ -44,7 +44,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test1", "test2", "test3"); } - @Test public void testSearchForWildcard() { //index1 is not authorized and referred to through wildcard createIndices("test1", "test2", "test3", "index1"); @@ -53,54 +52,70 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test1", "test2", "test3"); } - @Test(expected = IndexNotFoundException.class) public void testSearchNonAuthorizedWildcard() { //wildcard doesn't match any authorized index createIndices("test1", "test2", "index1", "index2"); - client().prepareSearch("index*").get(); + try { + client().prepareSearch("index*").get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testEmptyClusterSearchForAll() { - client().prepareSearch().get(); + try { + client().prepareSearch().get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testEmptyClusterSearchForWildcard() { - client().prepareSearch("*").get(); + try { + client().prepareSearch("*").get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testEmptyAuthorizedIndicesSearchForAll() { createIndices("index1", "index2"); - client().prepareSearch().get(); + try { + client().prepareSearch().get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test(expected = IndexNotFoundException.class) public void testEmptyAuthorizedIndicesSearchForWildcard() { createIndices("index1", "index2"); - client().prepareSearch("*").get(); + try { + client().prepareSearch("*").get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } - @Test public void testExplicitNonAuthorizedIndex() { createIndices("test1", "test2", "index1"); assertThrowsAuthorizationException(client().prepareSearch("test*", "index1")); } - @Test public void testIndexNotFound() { createIndices("test1", "test2", "index1"); assertThrowsAuthorizationException(client().prepareSearch("missing")); } - @Test public void testIndexNotFoundIgnoreUnavailable() { createIndices("test1", "test2", "index1"); assertThrowsAuthorizationException(client().prepareSearch("missing").setIndicesOptions(IndicesOptions.lenientExpandOpen())); } - @Test public void testExplicitExclusion() { //index1 is not authorized and referred to through wildcard, test2 is excluded createIndices("test1", "test2", "test3", "index1"); @@ -109,7 +124,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test1", "test3"); } - @Test public void testWildcardExclusion() { //index1 is not authorized and referred to through wildcard, test2 is excluded createIndices("test1", "test2", "test21", "test3", "index1"); @@ -118,7 +132,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test1", "test3"); } - @Test public void testInclusionAndWildcardsExclusion() { //index1 is not authorized and referred to through wildcard, test111 and test112 are excluded createIndices("test1", "test10", "test111", "test112", "test2", "index1"); @@ -127,7 +140,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test1", "test10"); } - @Test public void testExplicitAndWildcardsInclusionAndWildcardExclusion() { //index1 is not authorized and referred to through wildcard, test111 and test112 are excluded createIndices("test1", "test10", "test111", "test112", "test2", "index1"); @@ -136,7 +148,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test111", "test112"); } - @Test public void testExplicitAndWildcardInclusionAndExplicitExclusions() { //index1 is not authorized and referred to through wildcard, test111 and test112 are excluded createIndices("test1", "test10", "test111", "test112", "test2", "index1"); @@ -145,7 +156,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertReturnedIndices(searchResponse, "test10"); } - @Test public void testMultiSearchUnauthorizedIndex() { //index1 is not authorized, the whole request fails due to that createIndices("test1", "test2", "test3", "index1"); @@ -154,7 +164,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa .add(Requests.searchRequest("index1"))); } - @Test public void testMultiSearchMissingUnauthorizedIndex() { //index missing and not authorized, the whole request fails due to that createIndices("test1", "test2", "test3", "index1"); @@ -163,7 +172,6 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa .add(Requests.searchRequest("missing"))); } - @Test public void testMultiSearchMissingAuthorizedIndex() { //test4 is missing but authorized, only that specific item fails createIndices("test1", "test2", "test3", "index1"); @@ -174,13 +182,17 @@ public class IndicesAndAliasesResolverIntegrationTests extends ShieldIntegTestCa assertThat(multiSearchResponse.getResponses()[1].getFailure().toString(), equalTo("[test4] IndexNotFoundException[no such index]")); } - @Test(expected = IndexNotFoundException.class) public void testMultiSearchWildcard() { //test4 is missing but authorized, only that specific item fails createIndices("test1", "test2", "test3", "index1"); - client().prepareMultiSearch() - .add(Requests.searchRequest()) - .add(Requests.searchRequest("index*")).get(); + try { + client().prepareMultiSearch() + .add(Requests.searchRequest()) + .add(Requests.searchRequest("index*")).get(); + fail("Expected IndexNotFoundException"); + } catch (IndexNotFoundException e) { + assertThat(e.getMessage(), is("no such index")); + } } private static void assertReturnedIndices(SearchResponse searchResponse, String... indices) { diff --git a/shield/src/test/java/org/elasticsearch/shield/authz/store/FileRolesStoreTests.java b/shield/src/test/java/org/elasticsearch/shield/authz/store/FileRolesStoreTests.java index 7abcac78f03..3b4dfe7f941 100644 --- a/shield/src/test/java/org/elasticsearch/shield/authz/store/FileRolesStoreTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/authz/store/FileRolesStoreTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.shield.authz.Privilege; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; -import org.junit.Test; import java.io.BufferedWriter; import java.io.OutputStream; @@ -45,8 +44,6 @@ import static org.hamcrest.Matchers.startsWith; * */ public class FileRolesStoreTests extends ESTestCase { - - @Test public void testParseFile() throws Exception { Path path = getDataPath("roles.yml"); Map roles = FileRolesStore.parseFile(path, Collections.emptySet(), logger); @@ -148,7 +145,6 @@ public class FileRolesStoreTests extends ESTestCase { /** * This test is mainly to make sure we can read the default roles.yml config */ - @Test public void testDefaultRolesFile() throws Exception { Path path = getDataPath("default_roles.yml"); Map roles = FileRolesStore.parseFile(path, Collections.emptySet(), logger); @@ -165,7 +161,6 @@ public class FileRolesStoreTests extends ESTestCase { assertThat(roles, hasKey("marvel_agent")); } - @Test public void testAutoReload() throws Exception { ThreadPool threadPool = null; ResourceWatcherService watcherService = null; @@ -227,7 +222,6 @@ public class FileRolesStoreTests extends ESTestCase { } } - @Test public void testThatEmptyFileDoesNotResultInLoop() throws Exception { Path file = createTempFile(); Files.write(file, Collections.singletonList("#"), StandardCharsets.UTF_8); @@ -235,7 +229,6 @@ public class FileRolesStoreTests extends ESTestCase { assertThat(roles.keySet(), is(empty())); } - @Test public void testThatInvalidRoleDefinitions() throws Exception { Path path = getDataPath("invalid_roles.yml"); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.ERROR); @@ -255,7 +248,6 @@ public class FileRolesStoreTests extends ESTestCase { assertThat(entries.get(4).text, startsWith("invalid role definition [role4] in roles file [" + path.toAbsolutePath() + "]. could not resolve indices privileges [al;kjdlkj;lkj]")); } - @Test public void testThatRoleNamesDoesNotResolvePermissions() throws Exception { Path path = getDataPath("invalid_roles.yml"); CapturingLogger logger = new CapturingLogger(CapturingLogger.Level.ERROR); @@ -268,7 +260,6 @@ public class FileRolesStoreTests extends ESTestCase { assertThat(entries.get(0).text, startsWith("invalid role definition [$dlk39] in roles file [" + path.toAbsolutePath() + "]. invalid role name")); } - @Test public void testReservedRoles() throws Exception { Set reservedRoles = singleton(Permission.Global.Role.builder("reserved") .cluster(Privilege.Cluster.ALL) @@ -299,7 +290,6 @@ public class FileRolesStoreTests extends ESTestCase { assertThat(reserved.indices().isEmpty(), is(true)); } - @Test public void testReservedRolesNonExistentRolesFile() throws Exception { Set reservedRoles = singleton(Permission.Global.Role.builder("reserved") .cluster(Privilege.Cluster.ALL) diff --git a/shield/src/test/java/org/elasticsearch/shield/crypto/InternalCryptoServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/crypto/InternalCryptoServiceTests.java index 21f2c931e68..0992eddbf7a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/crypto/InternalCryptoServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/crypto/InternalCryptoServiceTests.java @@ -14,10 +14,7 @@ import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.junit.After; import org.junit.Before; -import org.junit.Test; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -28,13 +25,19 @@ import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * */ public class InternalCryptoServiceTests extends ESTestCase { - private ResourceWatcherService watcherService; private Settings settings; private Environment env; @@ -62,7 +65,6 @@ public class InternalCryptoServiceTests extends ESTestCase { terminate(threadPool); } - @Test public void testSigned() throws Exception { // randomize whether to use a system key or not Settings settings = randomBoolean() ? this.settings : Settings.EMPTY; @@ -72,7 +74,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(service.signed(signed), is(true)); } - @Test public void testSignAndUnsign() throws Exception { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); String text = randomAsciiOfLength(10); @@ -82,8 +83,7 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(text, equalTo(text2)); } - @Test - public void testSignAndUnsign_NoKeyFile() throws Exception { + public void testSignAndUnsignNoKeyFile() throws Exception { InternalCryptoService service = new InternalCryptoService(Settings.EMPTY, env, watcherService).start(); final String text = randomAsciiOfLength(10); String signed = service.sign(text); @@ -93,7 +93,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(unsigned, equalTo(text)); } - @Test public void testTamperedSignature() throws Exception { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); String text = randomAsciiOfLength(10); @@ -111,7 +110,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testTamperedSignatureOneChar() throws Exception { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); String text = randomAsciiOfLength(10); @@ -131,7 +129,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testTamperedSignatureLength() throws Exception { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); String text = randomAsciiOfLength(10); @@ -159,7 +156,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testEncryptionAndDecryptionChars() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -172,7 +168,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(Arrays.equals(chars, decrypted), is(true)); } - @Test public void testEncryptionAndDecryptionBytes() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -185,7 +180,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(Arrays.equals(bytes, decrypted), is(true)); } - @Test public void testEncryptionAndDecryptionCharsWithoutKey() { InternalCryptoService service = new InternalCryptoService(Settings.EMPTY, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(false)); @@ -196,7 +190,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(chars, equalTo(decryptedChars)); } - @Test public void testEncryptionAndDecryptionBytesWithoutKey() { InternalCryptoService service = new InternalCryptoService(Settings.EMPTY, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(false)); @@ -207,19 +200,16 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(decryptedBytes, equalTo(encryptedBytes)); } - @Test public void testEncryptionEnabledWithKey() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); } - @Test public void testEncryptionEnabledWithoutKey() { InternalCryptoService service = new InternalCryptoService(Settings.EMPTY, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(false)); } - @Test public void testChangingAByte() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -240,7 +230,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(Arrays.equals(bytes, decrypted), is(false)); } - @Test public void testEncryptedChar() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -253,7 +242,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(service.encrypted(service.encrypt(randomAsciiOfLength(10).toCharArray())), is(true)); } - @Test public void testEncryptedByte() { InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -266,7 +254,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(service.encrypted(service.encrypt(randomAsciiOfLength(10).getBytes(StandardCharsets.UTF_8))), is(true)); } - @Test public void testReloadKey() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final CryptoService.Listener listener = new CryptoService.Listener() { @@ -311,7 +298,6 @@ public class InternalCryptoServiceTests extends ESTestCase { assertThat(Arrays.equals(textChars, decrypted2), is(true)); } - @Test public void testReencryptValuesOnKeyChange() throws Exception { final InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -342,7 +328,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testResignValuesOnKeyChange() throws Exception { final InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); final String text = randomAsciiOfLength(10); @@ -377,7 +362,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testReencryptValuesOnKeyDeleted() throws Exception { final InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -408,7 +392,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testAllListenersCalledWhenExceptionThrown() throws Exception { final InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); assertThat(service.encryptionEnabled(), is(true)); @@ -444,7 +427,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testSigningOnKeyDeleted() throws Exception { final InternalCryptoService service = new InternalCryptoService(settings, env, watcherService).start(); final String text = randomAsciiOfLength(10); @@ -479,7 +461,6 @@ public class InternalCryptoServiceTests extends ESTestCase { } } - @Test public void testSigningKeyCanBeRecomputedConsistently() { final SecretKey systemKey = new SecretKeySpec(InternalCryptoService.generateKey(), InternalCryptoService.KEY_ALGO); final SecretKey randomKey = InternalCryptoService.generateSecretKey(InternalCryptoService.RANDOM_KEY_SIZE); diff --git a/shield/src/test/java/org/elasticsearch/shield/crypto/tool/SystemKeyToolTests.java b/shield/src/test/java/org/elasticsearch/shield/crypto/tool/SystemKeyToolTests.java index 481ed2919b1..fc2c699a4b6 100644 --- a/shield/src/test/java/org/elasticsearch/shield/crypto/tool/SystemKeyToolTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/crypto/tool/SystemKeyToolTests.java @@ -12,8 +12,8 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.shield.crypto.InternalCryptoService; +import org.elasticsearch.shield.crypto.tool.SystemKeyTool.Generate; import org.junit.Before; -import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; @@ -21,7 +21,6 @@ import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; -import static org.elasticsearch.shield.crypto.tool.SystemKeyTool.Generate; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; @@ -35,7 +34,6 @@ import static org.mockito.Mockito.when; * */ public class SystemKeyToolTests extends CliToolTestCase { - private Terminal terminal; private Environment env; @@ -47,16 +45,14 @@ public class SystemKeyToolTests extends CliToolTestCase { when(env.binFile()).thenReturn(tmpDir.resolve("bin")); } - @Test - public void testParse_NoArgs() throws Exception { + public void testParseNoArgs() throws Exception { CliTool.Command cmd = new SystemKeyTool().parse("generate", args("")); assertThat(cmd, instanceOf(Generate.class)); Generate generate = (Generate) cmd; assertThat(generate.path, nullValue()); } - @Test - public void testParse_FileArg() throws Exception { + public void testParseFileArg() throws Exception { Path path = createTempFile(); CliTool.Command cmd = new SystemKeyTool().parse("generate", new String[]{path.toAbsolutePath().toString()}); assertThat(cmd, instanceOf(Generate.class)); @@ -66,7 +62,6 @@ public class SystemKeyToolTests extends CliToolTestCase { assertThat(generate.path.toString(), equalTo(path.toString())); } - @Test public void testGenerate() throws Exception { Path path = createTempFile(); Generate generate = new Generate(terminal, path); @@ -76,8 +71,7 @@ public class SystemKeyToolTests extends CliToolTestCase { assertThat(bytes.length, is(InternalCryptoService.KEY_SIZE / 8)); } - @Test - public void testGenerate_PathInSettings() throws Exception { + public void testGeneratePathInSettings() throws Exception { Path path = createTempFile(); Settings settings = Settings.builder() .put("shield.system_key.file", path.toAbsolutePath().toString()) @@ -89,8 +83,7 @@ public class SystemKeyToolTests extends CliToolTestCase { assertThat(bytes.length, is(InternalCryptoService.KEY_SIZE / 8)); } - @Test - public void testGenerate_DefaultPath() throws Exception { + public void testGenerateDefaultPath() throws Exception { Path config = createTempDir(); Path shieldConfig = config.resolve(ShieldPlugin.NAME); Files.createDirectories(shieldConfig); @@ -103,7 +96,6 @@ public class SystemKeyToolTests extends CliToolTestCase { assertThat(bytes.length, is(InternalCryptoService.KEY_SIZE / 8)); } - @Test public void testThatSystemKeyMayOnlyBeReadByOwner() throws Exception { Path config = createTempDir(); Path shieldConfig = config.resolve(ShieldPlugin.NAME); diff --git a/shield/src/test/java/org/elasticsearch/shield/rest/ShieldRestFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/rest/ShieldRestFilterTests.java index 3a8272c0cb4..8903d2051e7 100644 --- a/shield/src/test/java/org/elasticsearch/shield/rest/ShieldRestFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/rest/ShieldRestFilterTests.java @@ -16,17 +16,18 @@ import org.elasticsearch.shield.authc.AuthenticationService; import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.shield.support.Exceptions.authenticationError; import static org.hamcrest.Matchers.equalTo; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * */ public class ShieldRestFilterTests extends ESTestCase { - private AuthenticationService authcService; private RestChannel channel; private RestFilterChain chain; @@ -45,7 +46,6 @@ public class ShieldRestFilterTests extends ESTestCase { verify(restController).registerFilter(filter); } - @Test public void testProcess() throws Exception { RestRequest request = mock(RestRequest.class); User user = new User.Simple("_user", new String[] { "r1" }); @@ -55,7 +55,6 @@ public class ShieldRestFilterTests extends ESTestCase { verifyZeroInteractions(channel); } - @Test public void testProcessBasicLicense() throws Exception { RestRequest request = mock(RestRequest.class); when(licenseState.securityEnabled()).thenReturn(false); @@ -64,8 +63,7 @@ public class ShieldRestFilterTests extends ESTestCase { verifyZeroInteractions(channel, authcService); } - @Test - public void testProcess_AuthenticationError() throws Exception { + public void testProcessAuthenticationError() throws Exception { RestRequest request = mock(RestRequest.class); when(authcService.authenticate(request)).thenThrow(authenticationError("failed authc")); try { @@ -78,8 +76,7 @@ public class ShieldRestFilterTests extends ESTestCase { verifyZeroInteractions(chain); } - @Test - public void testProcess_OptionsMethod() throws Exception { + public void testProcessOptionsMethod() throws Exception { RestRequest request = mock(RestRequest.class); when(request.method()).thenReturn(RestRequest.Method.OPTIONS); filter.process(request, channel, chain); diff --git a/shield/src/test/java/org/elasticsearch/shield/ssl/ClientSSLServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/ssl/ClientSSLServiceTests.java index 11496d1d2b3..813d5ac87f1 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ssl/ClientSSLServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ssl/ClientSSLServiceTests.java @@ -15,19 +15,32 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.junit.Before; -import org.junit.Test; -import javax.net.ssl.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; public class ClientSSLServiceTests extends ESTestCase { - Environment env; Path testclientStore; @@ -37,7 +50,6 @@ public class ClientSSLServiceTests extends ESTestCase { env = randomBoolean() ? new Environment(settingsBuilder().put("path.home", createTempDir()).build()) : null; } - @Test public void testThatInvalidProtocolThrowsException() throws Exception { try { new ClientSSLService(settingsBuilder() @@ -53,7 +65,6 @@ public class ClientSSLServiceTests extends ESTestCase { } } - @Test public void testThatCustomTruststoreCanBeSpecified() throws Exception { Path testnodeStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode.jks"); @@ -73,7 +84,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(sslEngineWithTruststore, is(not(sameInstance(sslEngine)))); } - @Test public void testThatSslContextCachingWorks() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) @@ -86,7 +96,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(sslContext, is(sameInstance(cachedSslContext))); } - @Test public void testThatKeyStoreAndKeyCanHaveDifferentPasswords() throws Exception { Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks"); createClientSSLService(settingsBuilder() @@ -96,7 +105,6 @@ public class ClientSSLServiceTests extends ESTestCase { .build()).createSSLEngine(); } - @Test public void testIncorrectKeyPasswordThrowsException() throws Exception { Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks"); try { @@ -110,7 +118,6 @@ public class ClientSSLServiceTests extends ESTestCase { } } - @Test public void testThatSSLv3IsNotEnabled() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) @@ -120,7 +127,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(Arrays.asList(engine.getEnabledProtocols()), not(hasItem("SSLv3"))); } - @Test public void testThatSSLSessionCacheHasDefaultLimits() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) @@ -131,7 +137,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(context.getSessionTimeout(), equalTo((int) TimeValue.timeValueHours(24).seconds())); } - @Test public void testThatSettingSSLSessionCacheLimitsWorks() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) @@ -144,14 +149,12 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(context.getSessionTimeout(), equalTo(600)); } - @Test public void testThatCreateClientSSLEngineWithoutAnySettingsWorks() throws Exception { ClientSSLService sslService = createClientSSLService(Settings.EMPTY); SSLEngine sslEngine = sslService.createSSLEngine(); assertThat(sslEngine, notNullValue()); } - @Test public void testThatCreateSSLEngineWithOnlyTruststoreWorks() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.truststore.path", testclientStore) @@ -161,7 +164,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(sslEngine, notNullValue()); } - @Test public void testThatCreateSSLEngineWithOnlyKeystoreWorks() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) @@ -171,7 +173,6 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(sslEngine, notNullValue()); } - @Test @Network public void testThatSSLContextWithoutSettingsWorks() throws Exception { ClientSSLService sslService = createClientSSLService(Settings.EMPTY); @@ -184,7 +185,6 @@ public class ClientSSLServiceTests extends ESTestCase { } } - @Test @Network public void testThatSSLContextWithKeystoreDoesNotTrustAllPublicCAs() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() @@ -203,24 +203,31 @@ public class ClientSSLServiceTests extends ESTestCase { } } - @Test(expected = IllegalArgumentException.class) public void testThatTruststorePasswordIsRequired() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.truststore.path", testclientStore) .build()); - sslService.sslContext(); + try { + sslService.sslContext(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no truststore password configured")); + } } - @Test(expected = IllegalArgumentException.class) public void testThatKeystorePasswordIsRequired() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) .build()); - sslService.sslContext(); + try { + sslService.sslContext(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no keystore password configured")); + } } - @Test - public void validCiphersAndInvalidCiphersWork() throws Exception { + public void testValidCiphersAndInvalidCiphersWork() throws Exception { List ciphers = new ArrayList<>(Arrays.asList(AbstractSSLService.DEFAULT_CIPHERS)); ciphers.add("foo"); ciphers.add("bar"); @@ -233,15 +240,18 @@ public class ClientSSLServiceTests extends ESTestCase { assertThat(Arrays.asList(enabledCiphers), not(contains("foo", "bar"))); } - @Test(expected = IllegalArgumentException.class) - public void invalidCiphersOnlyThrowsException() throws Exception { + public void testInvalidCiphersOnlyThrowsException() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .putArray("shield.ssl.ciphers", new String[] { "foo", "bar" }) .build()); - sslService.createSSLEngine(); + try { + sslService.createSSLEngine(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("failed loading cipher suites [[foo, bar]]")); + } } - @Test public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Exception { ClientSSLService sslService = createClientSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testclientStore) diff --git a/shield/src/test/java/org/elasticsearch/shield/ssl/SSLSettingsTests.java b/shield/src/test/java/org/elasticsearch/shield/ssl/SSLSettingsTests.java index 5f1d0bcc433..7bc330e443b 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ssl/SSLSettingsTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ssl/SSLSettingsTests.java @@ -9,17 +9,17 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.shield.ssl.AbstractSSLService.SSLSettings; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManagerFactory; import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; public class SSLSettingsTests extends ESTestCase { - - @Test public void testThatSSLSettingsWithEmptySettingsHaveCorrectDefaults() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, Settings.EMPTY); assertThat(sslSettings.keyStorePath, is(nullValue())); @@ -34,7 +34,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings.trustStorePath, is(nullValue())); } - @Test public void testThatOnlyKeystoreInSettingsSetsTruststoreSettings() { Settings settings = settingsBuilder() .put("shield.ssl.keystore.path", "path") @@ -59,7 +58,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.trustStorePassword, is(equalTo(sslSettings1.keyStorePassword))); } - @Test public void testThatKeystorePasswordIsDefaultKeyPassword() { Settings settings = settingsBuilder() .put("shield.ssl.keystore.password", "password") @@ -76,7 +74,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.keyPassword, is(equalTo(sslSettings1.keyStorePassword))); } - @Test public void testThatKeyPasswordCanBeSet() { Settings settings = settingsBuilder() .put("shield.ssl.keystore.password", "password") @@ -97,7 +94,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.keyPassword, is(equalTo("key"))); } - @Test public void testThatProfileSettingsOverrideServiceSettings() { Settings profileSettings = settingsBuilder() .put("keystore.path", "path") @@ -138,7 +134,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings.sessionCacheTimeout, is(equalTo(TimeValue.timeValueMinutes(10L)))); } - @Test public void testThatEmptySettingsAreEqual() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, Settings.EMPTY); SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, Settings.EMPTY); @@ -148,7 +143,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.equals(sslSettings1), is(equalTo(true))); } - @Test public void testThatSettingsWithDifferentKeystoresAreNotEqual() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.keystore.path", "path").build()); @@ -160,7 +154,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.equals(sslSettings1), is(equalTo(true))); } - @Test public void testThatSettingsWithDifferentProtocolsAreNotEqual() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.protocol", "ssl").build()); @@ -172,7 +165,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.equals(sslSettings1), is(equalTo(true))); } - @Test public void testThatSettingsWithDifferentTruststoresAreNotEqual() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.truststore.path", "/trust").build()); @@ -184,14 +176,12 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings1.equals(sslSettings1), is(equalTo(true))); } - @Test public void testThatEmptySettingsHaveSameHashCode() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, Settings.EMPTY); SSLSettings sslSettings1 = new SSLSettings(Settings.EMPTY, Settings.EMPTY); assertThat(sslSettings.hashCode(), is(equalTo(sslSettings1.hashCode()))); } - @Test public void testThatSettingsWithDifferentKeystoresHaveDifferentHashCode() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.keystore.path", "path").build()); @@ -200,7 +190,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings.hashCode(), is(not(equalTo(sslSettings1.hashCode())))); } - @Test public void testThatSettingsWithDifferentProtocolsHaveDifferentHashCode() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.protocol", "ssl").build()); @@ -209,7 +198,6 @@ public class SSLSettingsTests extends ESTestCase { assertThat(sslSettings.hashCode(), is(not(equalTo(sslSettings1.hashCode())))); } - @Test public void testThatSettingsWithDifferentTruststoresHaveDifferentHashCode() { SSLSettings sslSettings = new SSLSettings(Settings.EMPTY, settingsBuilder() .put("shield.ssl.truststore.path", "/trust").build()); diff --git a/shield/src/test/java/org/elasticsearch/shield/ssl/ServerSSLServiceTests.java b/shield/src/test/java/org/elasticsearch/shield/ssl/ServerSSLServiceTests.java index c98edbc417f..8633325fa76 100644 --- a/shield/src/test/java/org/elasticsearch/shield/ssl/ServerSSLServiceTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/ssl/ServerSSLServiceTests.java @@ -12,20 +12,31 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.shield.ShieldSettingsFilter; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; -import javax.net.ssl.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; public class ServerSSLServiceTests extends ESTestCase { - Path testnodeStore; ShieldSettingsFilter settingsFilter; Environment env; @@ -37,7 +48,6 @@ public class ServerSSLServiceTests extends ESTestCase { env = new Environment(settingsBuilder().put("path.home", createTempDir()).build()); } - @Test public void testThatInvalidProtocolThrowsException() throws Exception { Settings settings = settingsBuilder() .put("shield.ssl.protocol", "non-existing") @@ -54,7 +64,6 @@ public class ServerSSLServiceTests extends ESTestCase { } } - @Test public void testThatCustomTruststoreCanBeSpecified() throws Exception { Path testClientStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient.jks"); @@ -75,7 +84,6 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(sslEngineWithTruststore, is(not(sameInstance(sslEngine)))); } - @Test public void testThatSslContextCachingWorks() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) @@ -88,7 +96,6 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(sslContext, is(sameInstance(cachedSslContext))); } - @Test public void testThatKeyStoreAndKeyCanHaveDifferentPasswords() throws Exception { Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks"); new ServerSSLService(settingsBuilder() @@ -98,7 +105,6 @@ public class ServerSSLServiceTests extends ESTestCase { .build(), settingsFilter, env).createSSLEngine(); } - @Test public void testIncorrectKeyPasswordThrowsException() throws Exception { Path differentPasswordsStore = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testnode-different-passwords.jks"); try { @@ -112,7 +118,6 @@ public class ServerSSLServiceTests extends ESTestCase { } } - @Test public void testThatSSLv3IsNotEnabled() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) @@ -122,7 +127,6 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(Arrays.asList(engine.getEnabledProtocols()), not(hasItem("SSLv3"))); } - @Test public void testThatSSLSessionCacheHasDefaultLimits() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) @@ -133,7 +137,6 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(context.getSessionTimeout(), equalTo((int) TimeValue.timeValueHours(24).seconds())); } - @Test public void testThatSettingSSLSessionCacheLimitsWorks() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) @@ -146,42 +149,56 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(context.getSessionTimeout(), equalTo(600)); } - @Test(expected = IllegalArgumentException.class) public void testThatCreateSSLEngineWithoutAnySettingsDoesNotWork() throws Exception { ServerSSLService sslService = new ServerSSLService(Settings.EMPTY, settingsFilter, env); - sslService.createSSLEngine(); + try { + sslService.createSSLEngine(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no keystore configured")); + } } - @Test(expected = IllegalArgumentException.class) public void testThatCreateSSLEngineWithOnlyTruststoreDoesNotWork() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.truststore.path", testnodeStore) .put("shield.ssl.truststore.password", "testnode") .build(), settingsFilter, env); - SSLEngine sslEngine = sslService.createSSLEngine(); - assertThat(sslEngine, notNullValue()); + try { + sslService.createSSLEngine(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no keystore configured")); + } } - @Test(expected = IllegalArgumentException.class) public void testThatTruststorePasswordIsRequired() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) .put("shield.ssl.keystore.password", "testnode") .put("shield.ssl.truststore.path", testnodeStore) .build(), settingsFilter, env); - sslService.sslContext(); + try { + sslService.sslContext(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no truststore password configured")); + } } - @Test(expected = IllegalArgumentException.class) public void testThatKeystorePasswordIsRequired() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) .build(), settingsFilter, env); - sslService.sslContext(); + try { + sslService.sslContext(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("no keystore password configured")); + } } - @Test - public void validCiphersAndInvalidCiphersWork() throws Exception { + public void testCiphersAndInvalidCiphersWork() throws Exception { List ciphers = new ArrayList<>(Arrays.asList(AbstractSSLService.DEFAULT_CIPHERS)); ciphers.add("foo"); ciphers.add("bar"); @@ -196,17 +213,20 @@ public class ServerSSLServiceTests extends ESTestCase { assertThat(Arrays.asList(enabledCiphers), not(contains("foo", "bar"))); } - @Test(expected = IllegalArgumentException.class) - public void invalidCiphersOnlyThrowsException() throws Exception { + public void testInvalidCiphersOnlyThrowsException() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) .put("shield.ssl.keystore.password", "testnode") .putArray("shield.ssl.ciphers", new String[] { "foo", "bar" }) .build(), settingsFilter, env); - sslService.createSSLEngine(); + try { + sslService.createSSLEngine(); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("failed loading cipher suites [[foo, bar]]")); + } } - @Test public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Exception { ServerSSLService sslService = new ServerSSLService(settingsBuilder() .put("shield.ssl.keystore.path", testnodeStore) diff --git a/shield/src/test/java/org/elasticsearch/shield/support/AutomatonsTests.java b/shield/src/test/java/org/elasticsearch/shield/support/AutomatonsTests.java index f8d284728bf..fb29c709b0d 100644 --- a/shield/src/test/java/org/elasticsearch/shield/support/AutomatonsTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/support/AutomatonsTests.java @@ -7,26 +7,25 @@ package org.elasticsearch.shield.support; import dk.brics.automaton.Automaton; import dk.brics.automaton.RunAutomaton; -import org.elasticsearch.test.ESTestCase; -import org.junit.Test; -import static org.elasticsearch.shield.support.Automatons.*; +import org.elasticsearch.test.ESTestCase; + +import static org.elasticsearch.shield.support.Automatons.pattern; +import static org.elasticsearch.shield.support.Automatons.patterns; +import static org.elasticsearch.shield.support.Automatons.wildcard; import static org.hamcrest.Matchers.is; /** * */ public class AutomatonsTests extends ESTestCase { - - @Test - public void testPatterns_UnionOfMultiplePatterns() throws Exception { + public void testPatternsUnionOfMultiplePatterns() throws Exception { assertMatch(patterns("/fo.*/", "ba*"), "foo"); assertMatch(patterns("/fo.*/", "ba*"), "bar"); assertMismatch(patterns("/fo.*/", "ba*"), "zipfoo"); } - @Test - public void testPattern_Single() throws Exception { + public void testPatternSingle() throws Exception { assertMatch(pattern("/.*st/"), "test"); assertMatch(pattern("/t.*st/"), "test"); assertMatch(pattern("/tes*./"), "test"); @@ -48,7 +47,6 @@ public class AutomatonsTests extends ESTestCase { assertMatch(pattern("\\/test"), "/test"); } - @Test public void testWildcard() throws Exception { assertMatch(wildcard("*st"), "test"); assertMatch(wildcard("t*st"), "test"); diff --git a/shield/src/test/java/org/elasticsearch/shield/support/ShieldFilesTests.java b/shield/src/test/java/org/elasticsearch/shield/support/ShieldFilesTests.java index d4900e4db4b..e147575a86a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/support/ShieldFilesTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/support/ShieldFilesTests.java @@ -7,10 +7,10 @@ package org.elasticsearch.shield.support; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; + import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; @@ -22,13 +22,17 @@ import java.nio.file.attribute.PosixFilePermission; import java.util.Locale; import java.util.Set; -import static java.nio.file.attribute.PosixFilePermission.*; +import static java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE; +import static java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE; +import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE; +import static java.nio.file.attribute.PosixFilePermission.OWNER_READ; +import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; import static org.elasticsearch.shield.support.ShieldFiles.openAtomicMoveWriter; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; public class ShieldFilesTests extends ESTestCase { - - @Test public void testThatOriginalPermissionsAreKept() throws Exception { Path path = createTempFile(); @@ -53,7 +57,6 @@ public class ShieldFilesTests extends ESTestCase { assertThat(permissionsAfterWrite, is(perms)); } - @Test public void testThatOwnerAndGroupAreChanged() throws Exception { Configuration jimFsConfiguration = Configuration.unix().toBuilder().setAttributeViews("basic", "owner", "posix", "unix").build(); try (FileSystem fs = Jimfs.newFileSystem(jimFsConfiguration)) { diff --git a/shield/src/test/java/org/elasticsearch/shield/support/ValidationTests.java b/shield/src/test/java/org/elasticsearch/shield/support/ValidationTests.java index 25593c5a70c..db96f2ac1cf 100644 --- a/shield/src/test/java/org/elasticsearch/shield/support/ValidationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/support/ValidationTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.shield.support; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.Arrays; @@ -17,8 +16,6 @@ import static org.hamcrest.Matchers.nullValue; * */ public class ValidationTests extends ESTestCase { - - private static final char[] alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' @@ -49,15 +46,13 @@ public class ValidationTests extends ESTestCase { return newArray; } - @Test - public void testESUsers_validateUsername() throws Exception { + public void testESUsersValidateUsername() throws Exception { int length = randomIntBetween(1, 30); String name = new String(generateValidName(length)); assertThat(Validation.ESUsers.validateUsername(name), nullValue()); } - @Test - public void testESUsers_validateUsername_Invalid_Length() throws Exception { + public void testESUsersValidateUsernameInvalidLength() throws Exception { int length = frequently() ? randomIntBetween(31, 200) : 0; // invalid length char[] name = new char[length]; if (length > 0) { @@ -66,15 +61,13 @@ public class ValidationTests extends ESTestCase { assertThat(Validation.ESUsers.validateUsername(new String(name)), notNullValue()); } - @Test - public void testESUsers_validateUsername_Invalid_Characters() throws Exception { + public void testESUsersValidateUsernameInvalidCharacters() throws Exception { int length = randomIntBetween(1, 30); // valid length String name = new String(generateInvalidName(length)); assertThat(Validation.ESUsers.validateUsername(name), notNullValue()); } - @Test - public void testESUsers_validatePassword() throws Exception { + public void testESUsersValidatePassword() throws Exception { String passwd = randomAsciiOfLength(randomIntBetween(0, 20)); logger.info(passwd + "[{}]", passwd.length()); if (passwd.length() >= 6) { @@ -84,15 +77,13 @@ public class ValidationTests extends ESTestCase { } } - @Test - public void testRoles_validateRoleName() throws Exception { + public void testRolesValidateRoleName() throws Exception { int length = randomIntBetween(1, 30); String name = new String(generateValidName(length)); assertThat(Validation.Roles.validateRoleName(name), nullValue()); } - @Test - public void testRoles_validateRoleName_Invalid_Length() throws Exception { + public void testRolesValidateRoleNameInvalidLength() throws Exception { int length = frequently() ? randomIntBetween(31, 200) : 0; // invalid length char[] name = new char[length]; if (length > 0) { @@ -101,8 +92,7 @@ public class ValidationTests extends ESTestCase { assertThat(Validation.ESUsers.validateUsername(new String(name)), notNullValue()); } - @Test - public void testRoles_validateRoleName_Invalid_Characters() throws Exception { + public void testRolesValidateRoleNameInvalidCharacters() throws Exception { int length = randomIntBetween(1, 30); // valid length String name = new String(generateInvalidName(length)); assertThat(Validation.ESUsers.validateUsername(name), notNullValue()); @@ -118,11 +108,8 @@ public class ValidationTests extends ESTestCase { } private static char[] generateInvalidName(int length) { - if (length == 1 || randomBoolean()) { - - // invalid name due to charaters not allowed in the beginning of the name - + // invalid name due to characters not allowed in the beginning of the name char first; while (true) { first = randomUnicodeOfLength(1).charAt(0); @@ -138,7 +125,6 @@ public class ValidationTests extends ESTestCase { } // invalid name due to charaters not allowed within the name itself - char first = allowedFirstChars[randomIntBetween(0, allowedFirstChars.length - 1)]; char[] subsequent = new char[length - 1]; for (int i = 0; i < subsequent.length; i++) { @@ -153,6 +139,4 @@ public class ValidationTests extends ESTestCase { } return concat(new char[]{first}, subsequent); } - - } diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ClientTransportFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ClientTransportFilterTests.java index 4167a065932..dee14a7a33a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ClientTransportFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ClientTransportFilterTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.shield.authc.AuthenticationService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportRequest; import org.junit.Before; -import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -19,7 +18,6 @@ import static org.mockito.Mockito.verify; * */ public class ClientTransportFilterTests extends ESTestCase { - private AuthenticationService authcService; private ClientTransportFilter filter; @@ -29,7 +27,6 @@ public class ClientTransportFilterTests extends ESTestCase { filter = new ClientTransportFilter.Node(authcService); } - @Test public void testOutbound() throws Exception { TransportRequest request = mock(TransportRequest.class); filter.outbound("_action", request); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java index 6a69d1f32e1..63cd66b5445 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterIntegrationTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.transport.Transport; import org.junit.BeforeClass; -import org.junit.Test; import java.net.InetSocketAddress; import java.nio.file.Files; @@ -36,7 +35,6 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; public class ServerTransportFilterIntegrationTests extends ShieldIntegTestCase { - private static int randomClientPort; @BeforeClass @@ -78,7 +76,6 @@ public class ServerTransportFilterIntegrationTests extends ShieldIntegTestCase { .build(); } - @Test public void testThatConnectionToServerTypeConnectionWorks() { Settings dataNodeSettings = internalCluster().getDataNodeInstance(Settings.class); String systemKeyFile = dataNodeSettings.get(InternalCryptoService.FILE_SETTING); @@ -111,7 +108,6 @@ public class ServerTransportFilterIntegrationTests extends ShieldIntegTestCase { } } - @Test public void testThatConnectionToClientTypeConnectionIsRejected() { Settings dataNodeSettings = internalCluster().getDataNodeInstance(Settings.class); String systemKeyFile = dataNodeSettings.get(InternalCryptoService.FILE_SETTING); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterTests.java index 2e79d743e11..244e1b36036 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ServerTransportFilterTests.java @@ -15,18 +15,20 @@ import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.netty.NettyTransport; import org.elasticsearch.transport.netty.NettyTransportChannel; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.shield.support.Exceptions.authenticationError; import static org.elasticsearch.shield.support.Exceptions.authorizationError; import static org.hamcrest.Matchers.equalTo; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * */ public class ServerTransportFilterTests extends ESTestCase { - private AuthenticationService authcService; private AuthorizationService authzService; private ServerTransportFilter filter; @@ -41,7 +43,6 @@ public class ServerTransportFilterTests extends ESTestCase { filter = new ServerTransportFilter.NodeProfile(authcService, authzService, new ShieldActionMapper(), false); } - @Test public void testInbound() throws Exception { TransportRequest request = mock(TransportRequest.class); User user = mock(User.class); @@ -50,8 +51,7 @@ public class ServerTransportFilterTests extends ESTestCase { verify(authzService).authorize(user, "_action", request); } - @Test - public void testInbound_AuthenticationException() throws Exception { + public void testInboundAuthenticationException() throws Exception { TransportRequest request = mock(TransportRequest.class); doThrow(authenticationError("authc failed")).when(authcService).authenticate("_action", request, null); try { @@ -63,8 +63,7 @@ public class ServerTransportFilterTests extends ESTestCase { verifyZeroInteractions(authzService); } - @Test - public void testInbound_AuthorizationException() throws Exception { + public void testInboundAuthorizationException() throws Exception { TransportRequest request = mock(TransportRequest.class); User user = mock(User.class); when(authcService.authenticate("_action", request, null)).thenReturn(user); @@ -76,5 +75,4 @@ public class ServerTransportFilterTests extends ESTestCase { assertThat(e.getMessage(), equalTo("authz failed")); } } - } diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/TransportFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/TransportFilterTests.java index c2d2cbce353..6cf3d0e9f7a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/TransportFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/TransportFilterTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.shield.transport; -import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.AbstractModule; @@ -20,11 +19,19 @@ import org.elasticsearch.shield.authc.AuthenticationService; import org.elasticsearch.shield.authz.AuthorizationService; import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.test.ESIntegTestCase; +import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.transport.*; +import org.elasticsearch.transport.Transport; +import org.elasticsearch.transport.TransportChannel; +import org.elasticsearch.transport.TransportException; +import org.elasticsearch.transport.TransportModule; +import org.elasticsearch.transport.TransportRequest; +import org.elasticsearch.transport.TransportRequestHandler; +import org.elasticsearch.transport.TransportResponse; +import org.elasticsearch.transport.TransportResponseHandler; +import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.netty.NettyTransport; import org.elasticsearch.transport.netty.NettyTransportChannel; -import org.junit.Test; import org.mockito.InOrder; import java.io.IOException; @@ -35,18 +42,19 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.elasticsearch.test.ESIntegTestCase.ClusterScope; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * */ @ClusterScope(scope = SUITE, numDataNodes = 0) public class TransportFilterTests extends ESIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.settingsBuilder() @@ -69,7 +77,6 @@ public class TransportFilterTests extends ESIntegTestCase { return nodePlugins(); } - @Test public void test() throws Exception { String source = internalCluster().startNode(); DiscoveryNode sourceNode = internalCluster().getInstance(ClusterService.class, source).localNode(); @@ -103,7 +110,6 @@ public class TransportFilterTests extends ESIntegTestCase { } public static class InternalPlugin extends Plugin { - @Override public String name() { return "test-transport-filter"; @@ -130,7 +136,6 @@ public class TransportFilterTests extends ESIntegTestCase { } public static class Request extends TransportRequest { - private String msg; public Request() { @@ -222,7 +227,6 @@ public class TransportFilterTests extends ESIntegTestCase { } static class RequestHandler implements TransportRequestHandler { - private final Response response; private final CountDownLatch latch; @@ -239,7 +243,6 @@ public class TransportFilterTests extends ESIntegTestCase { } class ResponseHandler implements TransportResponseHandler { - private final Response response; private final CountDownLatch latch; @@ -303,6 +306,7 @@ public class TransportFilterTests extends ESIntegTestCase { when(licenseState.securityEnabled()).thenReturn(true); } + @Override protected Map initializeProfileFilters() { return Collections.singletonMap(NettyTransport.DEFAULT_PROFILE, mock(ServerTransportFilter.NodeProfile.class)); } diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IPFilterTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IPFilterTests.java index 8c92e710319..7fc03242658 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IPFilterTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IPFilterTests.java @@ -20,21 +20,27 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.elasticsearch.transport.Transport; import org.junit.Before; -import org.junit.Test; import org.mockito.ArgumentCaptor; import java.net.InetAddress; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.*; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * */ public class IPFilterTests extends ESTestCase { - private IPFilter ipFilter; private ShieldLicenseState licenseState; private AuditTrail auditTrail; @@ -64,7 +70,6 @@ public class IPFilterTests extends ESTestCase { when(transport.profileBoundAddresses()).thenReturn(profileBoundAddresses); } - @Test public void testThatIpV4AddressesCanBeProcessed() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "127.0.0.1") @@ -76,7 +81,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDenied("10.2.3.4"); } - @Test public void testThatIpV6AddressesCanBeProcessed() throws Exception { // you have to use the shortest possible notation in order to match, so // 1234:0db8:85a3:0000:0000:8a2e:0370:7334 becomes 1234:db8:85a3:0:0:8a2e:370:7334 @@ -91,7 +95,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDenied("4321:0db8:1234:0000:0000:8a2e:0370:7334"); } - @Test @Network // requires network for name resolution public void testThatHostnamesCanBeProcessed() throws Exception { Settings settings = settingsBuilder() @@ -104,7 +107,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDenied("8.8.8.8"); } - @Test public void testThatAnAllowAllAuthenticatorWorks() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "_all") @@ -115,7 +117,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsAllowed("173.194.70.100"); } - @Test public void testThatProfilesAreSupported() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "localhost") @@ -131,7 +132,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDeniedForProfile("client", "192.168.0.2"); } - @Test public void testThatAllowWinsOverDeny() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "10.0.0.1") @@ -143,7 +143,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDenied("10.0.0.2"); } - @Test public void testDefaultAllow() throws Exception { Settings settings = settingsBuilder().build(); ipFilter = new IPFilter(settings, auditTrail, nodeSettingsService, transport, licenseState).start(); @@ -152,7 +151,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsAllowed("10.0.0.2"); } - @Test public void testThatHttpWorks() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "127.0.0.1") @@ -167,7 +165,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDeniedForProfile(IPFilter.HTTP_PROFILE_NAME, "192.168.0.1"); } - @Test public void testThatHttpFallsbackToDefault() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.allow", "127.0.0.1") @@ -180,7 +177,6 @@ public class IPFilterTests extends ESTestCase { assertAddressIsDeniedForProfile(IPFilter.HTTP_PROFILE_NAME, "10.2.3.4"); } - @Test public void testThatBoundAddressIsNeverRejected() throws Exception { List addressStrings = new ArrayList<>(); for (TransportAddress address : transport.boundAddress().boundAddresses()) { @@ -202,7 +198,6 @@ public class IPFilterTests extends ESTestCase { } } - @Test public void testThatAllAddressesAreAllowedWhenLicenseDisablesSecurity() { Settings settings = settingsBuilder() .put("shield.transport.filter.deny", "_all") diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringIntegrationTests.java index 65a78120596..7ee8af013a5 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringIntegrationTests.java @@ -11,10 +11,11 @@ import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.node.Node; +import org.elasticsearch.test.ESIntegTestCase.ClusterScope; +import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.transport.Transport; import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.io.OutputStream; @@ -23,15 +24,12 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; -import static org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import static org.elasticsearch.test.ESIntegTestCase.Scope; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; // no client nodes, no transport clients, as they all get rejected on network connections @ClusterScope(scope = Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0) public class IpFilteringIntegrationTests extends ShieldIntegTestCase { - private static int randomClientPort; @BeforeClass @@ -50,7 +48,6 @@ public class IpFilteringIntegrationTests extends ShieldIntegTestCase { .put("shield.http.filter.deny", "_all").build(); } - @Test public void testThatIpFilteringIsIntegratedIntoNettyPipelineViaHttp() throws Exception { TransportAddress transportAddress = randomFrom(internalCluster().getDataNodeInstance(HttpServerTransport.class).boundAddress().boundAddresses()); assertThat(transportAddress, is(instanceOf(InetSocketTransportAddress.class))); @@ -62,13 +59,11 @@ public class IpFilteringIntegrationTests extends ShieldIntegTestCase { } } - @Test public void testThatIpFilteringIsNotAppliedForDefaultTransport() throws Exception { Client client = internalCluster().transportClient(); assertGreenClusterState(client); } - @Test public void testThatIpFilteringIsAppliedForProfile() throws Exception { try (Socket socket = new Socket()){ trySocketConnection(socket, new InetSocketAddress(InetAddress.getLoopbackAddress(), getProfilePort("client"))); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringUpdateTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringUpdateTests.java index ccf8d251e78..ec658b00e77 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringUpdateTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/filter/IpFilteringUpdateTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.node.Node; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.junit.BeforeClass; -import org.junit.Test; import java.net.InetAddress; import java.net.UnknownHostException; @@ -24,7 +23,6 @@ import static org.hamcrest.Matchers.is; @ClusterScope(scope = TEST, numDataNodes = 1) public class IpFilteringUpdateTests extends ShieldIntegTestCase { - private static int randomClientPort; private final boolean httpEnabled = randomBoolean(); @@ -45,7 +43,6 @@ public class IpFilteringUpdateTests extends ShieldIntegTestCase { .build(); } - @Test public void testThatIpFilterConfigurationCanBeChangedDynamically() throws Exception { // ensure this did not get overwritten by the listener during startup assertConnectionRejected("default", "127.0.0.200"); @@ -119,7 +116,7 @@ public class IpFilteringUpdateTests extends ShieldIntegTestCase { } } - @Test // issue #762, occured because in the above test we use HTTP and transport + // issue #762, occured because in the above test we use HTTP and transport public void testThatDisablingIpFilterWorksAsExpected() throws Exception { Settings settings = settingsBuilder() .put("shield.transport.filter.deny", "127.0.0.8") @@ -134,7 +131,6 @@ public class IpFilteringUpdateTests extends ShieldIntegTestCase { assertConnectionAccepted("default", "127.0.0.8"); } - @Test public void testThatDisablingIpFilterForProfilesWorksAsExpected() throws Exception { Settings settings = settingsBuilder() .put("transport.profiles.client.shield.filter.deny", "127.0.0.8") diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/filter/ShieldIpFilterRuleTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/filter/ShieldIpFilterRuleTests.java index 6469ff74f8d..dc71f017583 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/filter/ShieldIpFilterRuleTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/filter/ShieldIpFilterRuleTests.java @@ -9,9 +9,10 @@ import org.elasticsearch.test.ESTestCase; import org.jboss.netty.handler.ipfilter.IpFilterRule; import org.jboss.netty.handler.ipfilter.IpSubnetFilterRule; import org.jboss.netty.handler.ipfilter.PatternRule; -import org.junit.Test; -import static org.elasticsearch.shield.transport.filter.ShieldIpFilterRule.*; +import static org.elasticsearch.shield.transport.filter.ShieldIpFilterRule.ACCEPT_ALL; +import static org.elasticsearch.shield.transport.filter.ShieldIpFilterRule.DENY_ALL; +import static org.elasticsearch.shield.transport.filter.ShieldIpFilterRule.getRule; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.sameInstance; @@ -20,8 +21,6 @@ import static org.hamcrest.Matchers.sameInstance; * Unit tests for the {@link ShieldIpFilterRule} */ public class ShieldIpFilterRuleTests extends ESTestCase { - - @Test public void testParseAllRules() { IpFilterRule rule = getRule(true, "_all"); assertThat(rule, sameInstance(ACCEPT_ALL)); @@ -30,7 +29,6 @@ public class ShieldIpFilterRuleTests extends ESTestCase { assertThat(rule, sameInstance(DENY_ALL)); } - @Test public void testParseAllRuleWithOtherValues() { String ruleValue = "_all," + randomFrom("name", "127.0.0.1", "127.0.0.0/24"); try { @@ -41,7 +39,6 @@ public class ShieldIpFilterRuleTests extends ESTestCase { } } - @Test public void testParseIpSubnetFilterRule() throws Exception { final boolean allow = randomBoolean(); IpFilterRule rule = getRule(allow, "127.0.0.0/24"); @@ -51,7 +48,6 @@ public class ShieldIpFilterRuleTests extends ESTestCase { assertThat(ipSubnetFilterRule.contains("127.0.0.1"), equalTo(true)); } - @Test public void testParseIpSubnetFilterRuleWithOtherValues() throws Exception { try { getRule(randomBoolean(), "127.0.0.0/24," + randomFrom("name", "127.0.0.1", "192.0.0.0/24")); @@ -61,7 +57,6 @@ public class ShieldIpFilterRuleTests extends ESTestCase { } } - @Test public void testParsePatternRules() { final boolean allow = randomBoolean(); String ruleSpec = "127.0.0.1,::1,192.168.0.*,name*,specific_name"; diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/HandshakeWaitingHandlerTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/HandshakeWaitingHandlerTests.java index 5fbc27b0cda..96dafbd679c 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/HandshakeWaitingHandlerTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/HandshakeWaitingHandlerTests.java @@ -16,17 +16,21 @@ import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.*; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.ssl.SslHandler; import org.junit.After; import org.junit.Before; -import org.junit.Test; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; @@ -41,11 +45,16 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLException; + import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; public class HandshakeWaitingHandlerTests extends ESTestCase { - private static final int CONCURRENT_CLIENT_REQUESTS = 20; private int iterations; @@ -95,10 +104,8 @@ public class HandshakeWaitingHandlerTests extends ESTestCase { failureCause = null; } - @Test public void testWriteBeforeHandshakeFailsWithoutHandler() throws Exception { clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { - @Override public ChannelPipeline getPipeline() throws Exception { final SSLEngine engine = sslContext.createSSLEngine(); @@ -130,7 +137,6 @@ public class HandshakeWaitingHandlerTests extends ESTestCase { assertThat("Expected this test to fail with an SSLException or AssertionError", failed.get(), is(true)); } - @Test @AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch-shield/issues/533") public void testWriteBeforeHandshakePassesWithHandshakeWaitingHandler() throws Exception { clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { @@ -205,6 +211,7 @@ public class HandshakeWaitingHandlerTests extends ESTestCase { private ChannelPipelineFactory getServerFactory() { return new ChannelPipelineFactory() { + @Override public ChannelPipeline getPipeline() throws Exception { final SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPFilterNettyUpstreamHandlerTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPFilterNettyUpstreamHandlerTests.java index 478bda5fa54..550aff91cfe 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPFilterNettyUpstreamHandlerTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPFilterNettyUpstreamHandlerTests.java @@ -18,9 +18,16 @@ import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.shield.transport.filter.IPFilter; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.Transport; -import org.jboss.netty.channel.*; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelConfig; +import org.jboss.netty.channel.ChannelEvent; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelHandler; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.UpstreamMessageEvent; import org.junit.Before; -import org.junit.Test; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -35,7 +42,6 @@ import static org.mockito.Mockito.when; * */ public class IPFilterNettyUpstreamHandlerTests extends ESTestCase { - private IPFilterNettyUpstreamHandler nettyUpstreamHandler; @Before @@ -72,7 +78,6 @@ public class IPFilterNettyUpstreamHandlerTests extends ESTestCase { } } - @Test public void testThatFilteringWorksByIp() throws Exception { InetSocketAddress localhostAddr = new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 12345); assertThat(nettyUpstreamHandler.accept(new NullChannelHandlerContext(), new UpstreamMessageEvent(new NullChannel(), "my message", localhostAddr), localhostAddr), is(true)); @@ -81,165 +86,204 @@ public class IPFilterNettyUpstreamHandlerTests extends ESTestCase { assertThat(nettyUpstreamHandler.accept(new NullChannelHandlerContext(), new UpstreamMessageEvent(new NullChannel(), "my message", remoteAddr), remoteAddr), is(false)); } - private static class NullChannelHandlerContext implements ChannelHandlerContext { + @Override public boolean canHandleDownstream() { return false; } + @Override public boolean canHandleUpstream() { return false; } + @Override public Object getAttachment() { return null; } + @Override public Channel getChannel() { return null; } + @Override public ChannelHandler getHandler() { return null; } + @Override public String getName() { return null; } + @Override public ChannelPipeline getPipeline() { return null; } + @Override public void sendDownstream(ChannelEvent e) { // NOOP } + @Override public void sendUpstream(ChannelEvent e) { // NOOP } + @Override public void setAttachment(Object attachment) { // NOOP } } private static class NullChannel implements Channel { + @Override public ChannelFuture bind(SocketAddress localAddress) { return null; } + @Override public ChannelFuture close() { return null; } + @Override public ChannelFuture connect(SocketAddress remoteAddress) { return null; } + @Override public ChannelFuture disconnect() { return null; } + @Override public ChannelFuture getCloseFuture() { return null; } + @Override public ChannelConfig getConfig() { return null; } + @Override public ChannelFactory getFactory() { return null; } + @Override public Integer getId() { return null; } + @Override public int getInterestOps() { return 0; } + @Override public SocketAddress getLocalAddress() { return null; } + @Override public Channel getParent() { return null; } + @Override public ChannelPipeline getPipeline() { return null; } + @Override public SocketAddress getRemoteAddress() { return null; } + @Override public boolean isBound() { return false; } + @Override public boolean isConnected() { return false; } + @Override public boolean isOpen() { return false; } + @Override public boolean isReadable() { return false; } + @Override public boolean isWritable() { return false; } + @Override public ChannelFuture setInterestOps(int interestOps) { return null; } + @Override public ChannelFuture setReadable(boolean readable) { return null; } + @Override public boolean getUserDefinedWritability(int i) { return false; } + @Override public void setUserDefinedWritability(int i, boolean b) { } + @Override public ChannelFuture unbind() { return null; } + @Override public ChannelFuture write(Object message) { return null; } + @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { return null; } + @Override public int compareTo(Channel o) { return 0; } + @Override public int hashCode() { return 0; } + @Override public boolean equals(Object o) { return this == o; } + @Override public Object getAttachment() { return null; } + @Override public void setAttachment(Object attachment) { // NOOP } diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPHostnameVerificationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPHostnameVerificationTests.java index 0a51a03f935..5f95767b821 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPHostnameVerificationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/IPHostnameVerificationTests.java @@ -8,7 +8,6 @@ package org.elasticsearch.shield.transport.netty; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ShieldIntegTestCase; -import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; @@ -17,7 +16,6 @@ import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.CoreMatchers.is; public class IPHostnameVerificationTests extends ShieldIntegTestCase { - Path keystore; @Override @@ -71,7 +69,6 @@ public class IPHostnameVerificationTests extends ShieldIntegTestCase { .build(); } - @Test public void testTransportClientConnectionWorksWithIPOnlyHostnameVerification() throws Exception { Client client = internalCluster().transportClient(); assertGreenClusterState(client); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyHttpServerTransportTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyHttpServerTransportTests.java index 55232bcc2a3..f626f7de5a4 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyHttpServerTransportTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyHttpServerTransportTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.test.ESTestCase; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.ssl.SslHandler; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.util.Locale; @@ -29,7 +28,6 @@ import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; public class ShieldNettyHttpServerTransportTests extends ESTestCase { - private ServerSSLService serverSSLService; @Before @@ -44,7 +42,6 @@ public class ShieldNettyHttpServerTransportTests extends ESTestCase { serverSSLService = new ServerSSLService(settings, settingsFilter, env); } - @Test public void testDefaultClientAuth() throws Exception { Settings settings = Settings.builder().put(ShieldNettyHttpServerTransport.HTTP_SSL_SETTING, true).build(); ShieldNettyHttpServerTransport transport = new ShieldNettyHttpServerTransport(settings, mock(NetworkService.class), mock(BigArrays.class), mock(IPFilter.class), serverSSLService); @@ -54,7 +51,6 @@ public class ShieldNettyHttpServerTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testOptionalClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.OPTIONAL.name(), SSLClientAuth.OPTIONAL.name().toLowerCase(Locale.ROOT)); Settings settings = Settings.builder() @@ -67,7 +63,6 @@ public class ShieldNettyHttpServerTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(true)); } - @Test public void testRequiredClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.REQUIRED.name(), SSLClientAuth.REQUIRED.name().toLowerCase(Locale.ROOT), "true", "TRUE"); Settings settings = Settings.builder() @@ -80,7 +75,6 @@ public class ShieldNettyHttpServerTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testNoClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.NO.name(), SSLClientAuth.NO.name().toLowerCase(Locale.ROOT), "false", "FALSE"); Settings settings = Settings.builder() diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyTransportTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyTransportTests.java index 43479547a20..245ed61a71e 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyTransportTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/ShieldNettyTransportTests.java @@ -22,17 +22,17 @@ import org.elasticsearch.transport.netty.NettyMockUtil; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.ssl.SslHandler; import org.junit.Before; -import org.junit.Test; import java.nio.file.Path; import java.util.Locale; import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; public class ShieldNettyTransportTests extends ESTestCase { - private ServerSSLService serverSSLService; private ClientSSLService clientSSLService; private ShieldSettingsFilter settingsFilter; @@ -51,7 +51,6 @@ public class ShieldNettyTransportTests extends ESTestCase { clientSSLService.setEnvironment(env); } - @Test public void testThatSSLCanBeDisabledByProfile() throws Exception { Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); ShieldNettyTransport transport = new ShieldNettyTransport(settings, mock(ThreadPool.class), mock(NetworkService.class), mock(BigArrays.class), Version.CURRENT, null, serverSSLService, clientSSLService, settingsFilter, mock(NamedWriteableRegistry.class)); @@ -60,7 +59,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class), nullValue()); } - @Test public void testThatSSLCanBeEnabledByProfile() throws Exception { Settings settings = settingsBuilder().put("shield.transport.ssl", false).build(); ShieldNettyTransport transport = new ShieldNettyTransport(settings, mock(ThreadPool.class), mock(NetworkService.class), mock(BigArrays.class), Version.CURRENT, null, serverSSLService, clientSSLService, settingsFilter, mock(NamedWriteableRegistry.class)); @@ -69,7 +67,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class), notNullValue()); } - @Test public void testThatProfileTakesDefaultSSLSetting() throws Exception { Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); ShieldNettyTransport transport = new ShieldNettyTransport(settings, mock(ThreadPool.class), mock(NetworkService.class), mock(BigArrays.class), Version.CURRENT, null, serverSSLService, clientSSLService, settingsFilter, mock(NamedWriteableRegistry.class)); @@ -78,7 +75,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine(), notNullValue()); } - @Test public void testDefaultClientAuth() throws Exception { Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); ShieldNettyTransport transport = new ShieldNettyTransport(settings, mock(ThreadPool.class), mock(NetworkService.class), mock(BigArrays.class), Version.CURRENT, null, serverSSLService, clientSSLService, settingsFilter, mock(NamedWriteableRegistry.class)); @@ -88,7 +84,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testRequiredClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.REQUIRED.name(), SSLClientAuth.REQUIRED.name().toLowerCase(Locale.ROOT), "true"); Settings settings = settingsBuilder() @@ -101,7 +96,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testNoClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.NO.name(), "false", "FALSE", SSLClientAuth.NO.name().toLowerCase(Locale.ROOT)); Settings settings = settingsBuilder() @@ -114,7 +108,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testOptionalClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.OPTIONAL.name(), SSLClientAuth.OPTIONAL.name().toLowerCase(Locale.ROOT)); Settings settings = settingsBuilder() @@ -127,7 +120,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(true)); } - @Test public void testProfileRequiredClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.REQUIRED.name(), SSLClientAuth.REQUIRED.name().toLowerCase(Locale.ROOT), "true", "TRUE"); Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); @@ -138,7 +130,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testProfileNoClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.NO.name(), "false", "FALSE", SSLClientAuth.NO.name().toLowerCase(Locale.ROOT)); Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); @@ -149,7 +140,6 @@ public class ShieldNettyTransportTests extends ESTestCase { assertThat(factory.getPipeline().get(SslHandler.class).getEngine().getWantClientAuth(), is(false)); } - @Test public void testProfileOptionalClientAuth() throws Exception { String value = randomFrom(SSLClientAuth.OPTIONAL.name(), SSLClientAuth.OPTIONAL.name().toLowerCase(Locale.ROOT)); Settings settings = settingsBuilder().put("shield.transport.ssl", true).build(); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/netty/SslHostnameVerificationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/netty/SslHostnameVerificationTests.java index d5e82967f71..41646cfc646 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/netty/SslHostnameVerificationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/netty/SslHostnameVerificationTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.transport.Transport; -import org.junit.Test; import java.net.InetSocketAddress; import java.nio.file.Files; @@ -22,9 +21,9 @@ import java.nio.file.Path; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.containsString; public class SslHostnameVerificationTests extends ShieldIntegTestCase { - @Override protected boolean sslTransportEnabled() { return true; @@ -65,7 +64,6 @@ public class SslHostnameVerificationTests extends ShieldIntegTestCase { .build(); } - @Test(expected = NoNodeAvailableException.class) public void testThatHostnameMismatchDeniesTransportClientConnection() throws Exception { Transport transport = internalCluster().getDataNodeInstance(Transport.class); TransportAddress transportAddress = transport.boundAddress().publishAddress(); @@ -80,10 +78,11 @@ public class SslHostnameVerificationTests extends ShieldIntegTestCase { client.addTransportAddress(new InetSocketTransportAddress(inetSocketAddress.getAddress(), inetSocketAddress.getPort())); client.admin().cluster().prepareHealth().get(); fail("Expected a NoNodeAvailableException due to hostname verification failures"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#")); } } - @Test public void testTransportClientConnectionIgnoringHostnameVerification() throws Exception { Client client = internalCluster().transportClient(); assertGreenClusterState(client); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java index bbd0b8e2f1f..a2bbeff457d 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java @@ -23,19 +23,18 @@ import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.transport.Transport; -import org.junit.Test; -import javax.net.ssl.SSLHandshakeException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import javax.net.ssl.SSLHandshakeException; + import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.hamcrest.Matchers.containsString; public class SslClientAuthTests extends ShieldIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return settingsBuilder() @@ -54,7 +53,6 @@ public class SslClientAuthTests extends ShieldIntegTestCase { return true; } - @Test(expected = SSLHandshakeException.class) public void testThatHttpFailsWithoutSslClientAuth() throws IOException { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( SSLContexts.createDefault(), @@ -62,14 +60,18 @@ public class SslClientAuthTests extends ShieldIntegTestCase { CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); - new HttpRequestBuilder(client) - .httpTransport(internalCluster().getInstance(HttpServerTransport.class)) - .method("GET").path("/") - .protocol("https") - .execute(); + try { + new HttpRequestBuilder(client) + .httpTransport(internalCluster().getInstance(HttpServerTransport.class)) + .method("GET").path("/") + .protocol("https") + .execute(); + fail("Expected SSLHandshakeException"); + } catch (SSLHandshakeException e) { + assertThat(e.getMessage(), containsString("unable to find valid certification path to requested target")); + } } - @Test public void testThatHttpWorksWithSslClientAuth() throws IOException { Settings settings = settingsBuilder().put(ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient.jks", "testclient")).build(); ClientSSLService sslService = new ClientSSLService(settings); @@ -89,7 +91,6 @@ public class SslClientAuthTests extends ShieldIntegTestCase { assertThat(response.getBody(), containsString("You Know, for Search")); } - @Test public void testThatTransportWorksWithoutSslClientAuth() throws Exception { // specify an arbitrary keystore, that does not include the certs needed to connect to the transport protocol Path store = getDataPath("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient-client-profile.jks"); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslIntegrationTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslIntegrationTests.java index 82eebbd28a0..fe2b4d013c8 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslIntegrationTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslIntegrationTests.java @@ -27,22 +27,23 @@ import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.transport.Transport; -import org.junit.Test; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.TrustManagerFactory; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.SecureRandom; import java.util.Locale; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.TrustManagerFactory; + import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; public class SslIntegrationTests extends ShieldIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return settingsBuilder().put(super.nodeSettings(nodeOrdinal)) @@ -56,9 +57,8 @@ public class SslIntegrationTests extends ShieldIntegTestCase { } // no SSL exception as this is the exception is returned when connecting - @Test(expected = NoNodeAvailableException.class) public void testThatUnconfiguredCiphersAreRejected() { - try(TransportClient transportClient = TransportClient.builder().settings(settingsBuilder() + try (TransportClient transportClient = TransportClient.builder().settings(settingsBuilder() .put(transportClientSettings()) .put("name", "programmatic_transport_client") .put("cluster.name", internalCluster().getClusterName()) @@ -69,11 +69,13 @@ public class SslIntegrationTests extends ShieldIntegTestCase { transportClient.addTransportAddress(transportAddress); transportClient.admin().cluster().prepareHealth().get(); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#")); } } // no SSL exception as this is the exception is returned when connecting - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientUsingSSLv3ProtocolIsRejected() { try(TransportClient transportClient = TransportClient.builder().settings(settingsBuilder() .put(transportClientSettings()) @@ -86,10 +88,12 @@ public class SslIntegrationTests extends ShieldIntegTestCase { transportClient.addTransportAddress(transportAddress); transportClient.admin().cluster().prepareHealth().get(); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#")); } } - @Test public void testThatConnectionToHTTPWorks() throws Exception { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient.jks", "testclient"); ClientSSLService service = new ClientSSLService(settings); @@ -104,7 +108,6 @@ public class SslIntegrationTests extends ShieldIntegTestCase { } } - @Test public void testThatHttpUsingSSLv3IsRejected() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); diff --git a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslMultiPortTests.java b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslMultiPortTests.java index ed08297c307..74b5692b03a 100644 --- a/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslMultiPortTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslMultiPortTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; import org.elasticsearch.transport.Transport; import org.junit.BeforeClass; -import org.junit.Test; import java.net.InetAddress; import java.nio.file.Files; @@ -25,6 +24,7 @@ import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_PASSWORD; import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_USER_NAME; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.containsString; public class SslMultiPortTests extends ShieldIntegTestCase { @@ -99,7 +99,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * Uses the internal cluster's transport client to test connection to the default profile. The internal transport * client uses the same SSL settings as the default profile so a connection should always succeed */ - @Test public void testThatStandardTransportClientCanConnectToDefaultProfile() throws Exception { assertGreenClusterState(internalCluster().transportClient()); } @@ -111,7 +110,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * connection should always succeed as the settings are the same as the default profile except for the port and * disabling the client auth requirement */ - @Test public void testThatStandardTransportClientCanConnectToNoClientAuthProfile() throws Exception { try(TransportClient transportClient = createTransportClient(Settings.EMPTY)) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_client_auth"))); @@ -126,11 +124,13 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * keystore so this connection will fail as the certificate presented by the standard transport client is not trusted * by this profile */ - @Test(expected = NoNodeAvailableException.class) public void testThatStandardTransportClientCannotConnectToClientProfile() throws Exception { - try(TransportClient transportClient = createTransportClient(Settings.EMPTY)) { + try (TransportClient transportClient = createTransportClient(Settings.EMPTY)) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("client"))); transportClient.admin().cluster().prepareHealth().get(); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -139,11 +139,13 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * no_ssl profile. The internal transport client is not used here since we are connecting to a different * profile. The no_ssl profile is plain text and the standard transport client uses SSL, so a connection will never work */ - @Test(expected = NoNodeAvailableException.class) public void testThatStandardTransportClientCannotConnectToNoSslProfile() throws Exception { try (TransportClient transportClient = createTransportClient(Settings.EMPTY)) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_ssl"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -152,7 +154,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate and had its own self signed certificate. This test connects to the client profile, which is only * set to trust the testclient-client-profile certificate so the connection should always succeed */ - @Test public void testThatProfileTransportClientCanConnectToClientProfile() throws Exception { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient-client-profile.jks", "testclient-client-profile"); try (TransportClient transportClient = createTransportClient(settings)) { @@ -167,7 +168,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * uses a truststore that does not trust the testclient-client-profile certificate but does not require client * authentication */ - @Test public void testThatProfileTransportClientCanConnectToNoClientAuthProfile() throws Exception { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient-client-profile.jks", "testclient-client-profile"); try (TransportClient transportClient = createTransportClient(settings)) { @@ -182,13 +182,15 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * uses a truststore that does not trust the testclient-client-profile certificate and requires client authentication * so the connection should always fail */ - @Test(expected = NoNodeAvailableException.class) public void testThatProfileTransportClientCannotConnectToDefaultProfile() throws Exception { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient-client-profile.jks", "testclient-client-profile"); try (TransportClient transportClient = createTransportClient(settings)) { TransportAddress transportAddress = randomFrom(internalCluster().getInstance(Transport.class).boundAddress().boundAddresses()); transportClient.addTransportAddress(transportAddress); transportClient.admin().cluster().prepareHealth().get(); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -197,19 +199,20 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate and had its own self signed certificate. This test connects to the no_ssl profile, which does not * use SSL so the connection will never work */ - @Test(expected = NoNodeAvailableException.class) public void testThatProfileTransportClientCannotConnectToNoSslProfile() throws Exception { Settings settings = ShieldSettingsSource.getSSLSettingsForStore("/org/elasticsearch/shield/transport/ssl/certs/simple/testclient-client-profile.jks", "testclient-client-profile"); try (TransportClient transportClient = createTransportClient(settings)) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_ssl"))); transportClient.admin().cluster().prepareHealth().get(); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } /** * Uses a transport client with SSL disabled. This test connects to the no_ssl profile, which should always succeed */ - @Test public void testThatTransportClientCanConnectToNoSslProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -225,7 +228,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * Uses a transport client with SSL disabled. This test connects to the default profile, which should always fail * as a non-ssl transport client cannot connect to a ssl profile */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientCannotConnectToDefaultProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -234,6 +236,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(randomFrom(internalCluster().getInstance(Transport.class).boundAddress().boundAddresses())); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -241,7 +246,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * Uses a transport client with SSL disabled. This test connects to the client profile, which should always fail * as a non-ssl transport client cannot connect to a ssl profile */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientCannotConnectToClientProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -250,6 +254,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("client"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -257,7 +264,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * Uses a transport client with SSL disabled. This test connects to the no_client_auth profile, which should always fail * as a non-ssl transport client cannot connect to a ssl profile */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientCannotConnectToNoClientAuthProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -266,6 +272,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_client_auth"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -274,7 +283,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate and contains no other certification. This test connects to the no_client_auth profile, which uses * the testnode certificate and does not require to present a certificate, so this connection should always succeed */ - @Test public void testThatTransportClientWithOnlyTruststoreCanConnectToNoClientAuthProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -295,7 +303,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * the testnode certificate and requires the client to present a certificate, so this connection will never work as * the client has no certificate to present */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientWithOnlyTruststoreCannotConnectToClientProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -307,6 +314,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("client"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -316,7 +326,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * the testnode certificate and requires the client to present a certificate, so this connection will never work as * the client has no certificate to present */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientWithOnlyTruststoreCannotConnectToDefaultProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -328,6 +337,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(randomFrom(internalCluster().getInstance(Transport.class).boundAddress().boundAddresses())); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -336,7 +348,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate and contains no other certification. This test connects to the no_ssl profile, which does not use * SSL so the connection should never succeed */ - @Test(expected = NoNodeAvailableException.class) public void testThatTransportClientWithOnlyTruststoreCannotConnectToNoSslProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -348,6 +359,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_ssl"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -356,7 +370,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate authorities. This test connects to the default profile, which uses a self-signed certificate that * will never be trusted by the default truststore so the connection should always fail */ - @Test(expected = NoNodeAvailableException.class) public void testThatSSLTransportClientWithNoTruststoreCannotConnectToDefaultProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -366,6 +379,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(randomFrom(internalCluster().getInstance(Transport.class).boundAddress().boundAddresses())); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -374,7 +390,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate authorities. This test connects to the client profile, which uses a self-signed certificate that * will never be trusted by the default truststore so the connection should always fail */ - @Test(expected = NoNodeAvailableException.class) public void testThatSSLTransportClientWithNoTruststoreCannotConnectToClientProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -384,6 +399,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("client"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -392,7 +410,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate authorities. This test connects to the no_client_auth profile, which uses a self-signed certificate that * will never be trusted by the default truststore so the connection should always fail */ - @Test(expected = NoNodeAvailableException.class) public void testThatSSLTransportClientWithNoTruststoreCannotConnectToNoClientAuthProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -402,6 +419,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_client_auth"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } @@ -410,7 +430,6 @@ public class SslMultiPortTests extends ShieldIntegTestCase { * certificate authorities. This test connects to the no_ssl profile, which does not use SSL so the connection * will not work */ - @Test(expected = NoNodeAvailableException.class) public void testThatSSLTransportClientWithNoTruststoreCannotConnectToNoSslProfile() throws Exception { Settings settings = settingsBuilder() .put("shield.user", DEFAULT_USER_NAME + ":" + DEFAULT_PASSWORD) @@ -420,6 +439,9 @@ public class SslMultiPortTests extends ShieldIntegTestCase { try (TransportClient transportClient = TransportClient.builder().settings(settings).build()) { transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getLoopbackAddress(), getProfilePort("no_ssl"))); assertGreenClusterState(transportClient); + fail("Expected NoNodeAvailableException"); + } catch (NoNodeAvailableException e) { + assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#-")); } } diff --git a/shield/src/test/java/org/elasticsearch/shield/tribe/TribeShieldLoadedTests.java b/shield/src/test/java/org/elasticsearch/shield/tribe/TribeShieldLoadedTests.java index a8c52b324f6..de3f1e53fcc 100644 --- a/shield/src/test/java/org/elasticsearch/shield/tribe/TribeShieldLoadedTests.java +++ b/shield/src/test/java/org/elasticsearch/shield/tribe/TribeShieldLoadedTests.java @@ -12,10 +12,8 @@ import org.elasticsearch.license.plugin.LicensePlugin; import org.elasticsearch.node.MockNode; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; -import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.Arrays; @@ -27,8 +25,6 @@ import static org.hamcrest.CoreMatchers.containsString; * shield too if the tribe node does. */ public class TribeShieldLoadedTests extends ESTestCase { - - @Test @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/13212") // we really need to support loading plugins at the node level this way which should flow the plugins down to the tribe service, right now it doesnt! public void testShieldLoadedOnBothTribeNodeAndClients() { @@ -42,7 +38,6 @@ public class TribeShieldLoadedTests extends ESTestCase { //this test causes leaking threads to be left behind @LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch/issues/9107") - @Test public void testShieldLoadedOnTribeNodeOnly() { //startup failure if any of the tribe clients doesn't have shield installed Settings.Builder builder = defaultSettings(); @@ -56,7 +51,6 @@ public class TribeShieldLoadedTests extends ESTestCase { } @LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elasticsearch/elasticsearch/issues/9107") - @Test public void testShieldMustBeLoadedOnAllTribes() { //startup failure if any of the tribe clients doesn't have shield installed Settings.Builder builder = addTribeSettings(defaultSettings(), "t2"); diff --git a/shield/src/test/java/org/elasticsearch/transport/KnownActionsTests.java b/shield/src/test/java/org/elasticsearch/transport/KnownActionsTests.java index 97b2204aac6..354ab2871fa 100644 --- a/shield/src/test/java/org/elasticsearch/transport/KnownActionsTests.java +++ b/shield/src/test/java/org/elasticsearch/transport/KnownActionsTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.shield.action.ShieldActionModule; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.junit.BeforeClass; -import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -54,7 +53,6 @@ public class KnownActionsTests extends ShieldIntegTestCase { codeActions = loadCodeActions(); } - @Test public void testAllTransportHandlersAreKnown() { TransportService transportService = internalCluster().getDataNodeInstance(TransportService.class); for (String handler : transportService.requestHandlers.keySet()) { @@ -64,21 +62,18 @@ public class KnownActionsTests extends ShieldIntegTestCase { } } - @Test public void testAllCodeActionsAreKnown() throws Exception { for (String action : codeActions) { assertThat("classpath action [" + action + "] is unknown to shield", knownActions, hasItem(action)); } } - @Test public void testAllKnownActionsAreValid() { for (String knownAction : knownActions) { assertThat("shield known action [" + knownAction + "] is not among the classpath actions", codeActions, hasItems(knownAction)); } } - @Test public void testAllKnownTransportHandlersAreValid() { TransportService transportService = internalCluster().getDataNodeInstance(TransportService.class); for (String knownHandler : knownHandlers) { diff --git a/watcher/src/main/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactory.java b/watcher/src/main/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactory.java index 31ad4fb3c11..489e9f14571 100644 --- a/watcher/src/main/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactory.java +++ b/watcher/src/main/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactory.java @@ -42,7 +42,7 @@ public class HipChatActionFactory extends ActionFactory { - private final TextTemplateEngine templateEngine; private final SlackService slackService; @@ -43,7 +42,7 @@ public class SlackActionFactory extends ActionFactory data = singletonMap("key", "value"); Attachment attachment = DataAttachment.JSON.create(data); InputStream input = attachment.bodyPart().getDataHandler().getInputStream(); @@ -32,8 +29,7 @@ public class DataAttachmentTests extends ESTestCase { assertThat(content, is("{\n \"key\" : \"value\"\n}")); } - @Test - public void testCreate_Yaml() throws Exception { + public void testCreateYaml() throws Exception { Map data = singletonMap("key", "value"); Attachment attachment = DataAttachment.YAML.create(data); InputStream input = attachment.bodyPart().getDataHandler().getInputStream(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionIntegrationTests.java index f3ab878d70a..7dc80ff593c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionIntegrationTests.java @@ -16,13 +16,12 @@ import org.elasticsearch.watcher.client.WatcherClient; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.trigger.schedule.IntervalSchedule; import org.junit.After; -import org.junit.Test; - -import javax.mail.internet.MimeMessage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import javax.mail.internet.MimeMessage; + import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; @@ -39,7 +38,6 @@ import static org.hamcrest.Matchers.equalTo; @ESIntegTestCase.ClusterScope(scope = SUITE, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 1) @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class EmailActionIntegrationTests extends AbstractWatcherIntegrationTestCase { - static final String USERNAME = "_user"; static final String PASSWORD = "_passwd"; @@ -66,7 +64,6 @@ public class EmailActionIntegrationTests extends AbstractWatcherIntegrationTestC .build(); } - @Test public void testArrayAccess() throws Exception { final CountDownLatch latch = new CountDownLatch(1); server.addListener(new EmailServer.Listener() { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java index 526aea25db7..21131c2d5b8 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailActionTests.java @@ -30,7 +30,6 @@ import org.elasticsearch.watcher.support.xcontent.WatcherParams; import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.HashMap; import java.util.Map; @@ -40,6 +39,7 @@ import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContextBuilder; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.instanceOf; @@ -53,8 +53,6 @@ import static org.mockito.Mockito.when; * */ public class EmailActionTests extends ESTestCase { - - @Test public void testExecute() throws Exception { final String account = "account1"; EmailService service = new EmailService() { @@ -152,7 +150,6 @@ public class EmailActionTests extends ESTestCase { } } - @Test public void testParser() throws Exception { TextTemplateEngine engine = mock(TextTemplateEngine.class); HtmlSanitizer htmlSanitizer = mock(HtmlSanitizer.class); @@ -299,8 +296,7 @@ public class EmailActionTests extends ESTestCase { return templates; } - @Test - public void testParser_SelfGenerated() throws Exception { + public void testParserSelfGenerated() throws Exception { EmailService service = mock(EmailService.class); TextTemplateEngine engine = mock(TextTemplateEngine.class); HtmlSanitizer htmlSanitizer = mock(HtmlSanitizer.class); @@ -368,16 +364,19 @@ public class EmailActionTests extends ESTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { EmailService emailService = mock(EmailService.class); TextTemplateEngine engine = mock(TextTemplateEngine.class); HtmlSanitizer htmlSanitizer = mock(HtmlSanitizer.class); XContentBuilder builder = jsonBuilder().startObject().field("unknown_field", "value"); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - new EmailActionFactory(Settings.EMPTY, emailService, engine, htmlSanitizer) - .parseExecutable(randomAsciiOfLength(3), randomAsciiOfLength(7), parser); + try { + new EmailActionFactory(Settings.EMPTY, emailService, engine, htmlSanitizer) + .parseExecutable(randomAsciiOfLength(3), randomAsciiOfLength(7), parser); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("unexpected string field [unknown_field]")); + } } static DataAttachment randomDataAttachment() { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailSecretsIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailSecretsIntegrationTests.java index 2706f2764ca..b7160dcf4b9 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailSecretsIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/EmailSecretsIntegrationTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.watcher.actions.email; import org.elasticsearch.action.get.GetResponse; -import org.joda.time.DateTime; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.watcher.actions.email.service.EmailTemplate; @@ -22,28 +21,32 @@ import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.watcher.trigger.TriggerEvent; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.WatchStore; +import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.After; -import org.junit.Test; -import javax.mail.internet.MimeMessage; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import javax.mail.internet.MimeMessage; + import static org.elasticsearch.watcher.actions.ActionBuilders.emailAction; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondition; import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * */ public class EmailSecretsIntegrationTests extends AbstractWatcherIntegrationTestCase { - static final String USERNAME = "_user"; static final String PASSWORD = "_passwd"; @@ -73,7 +76,6 @@ public class EmailSecretsIntegrationTests extends AbstractWatcherIntegrationTest .build(); } - @Test public void testEmail() throws Exception { WatcherClient watcherClient = watcherClient(); watcherClient.preparePutWatch("_id") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java index 4c77f97ec0d..ad061e22b6c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountTests.java @@ -12,23 +12,27 @@ import org.elasticsearch.watcher.support.secret.Secret; import org.elasticsearch.watcher.support.secret.SecretService; import org.junit.After; import org.junit.Before; -import org.junit.Test; + +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import javax.mail.Address; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; /** * */ public class AccountTests extends ESTestCase { - static final String USERNAME = "_user"; static final String PASSWORD = "_passwd"; @@ -44,7 +48,6 @@ public class AccountTests extends ESTestCase { server.stop(); } - @Test public void testConfig() throws Exception { String accountName = "_name"; @@ -152,7 +155,6 @@ public class AccountTests extends ESTestCase { assertThat(config.smtp.properties, equalTo(smtpProps)); } - @Test public void testSend() throws Exception { Account account = new Account(new Account.Config("default", Settings.builder() .put("smtp.host", "localhost") @@ -192,8 +194,7 @@ public class AccountTests extends ESTestCase { handle.remove(); } - @Test - public void testSend_CC_BCC() throws Exception { + public void testSendCCAndBCC() throws Exception { Account account = new Account(new Account.Config("default", Settings.builder() .put("smtp.host", "localhost") .put("smtp.port", server.port()) @@ -237,8 +238,7 @@ public class AccountTests extends ESTestCase { handle.remove(); } - @Test - public void testSend_Authentication() throws Exception { + public void testSendAuthentication() throws Exception { Account account = new Account(new Account.Config("default", Settings.builder() .put("smtp.host", "localhost") .put("smtp.port", server.port()) @@ -268,5 +268,4 @@ public class AccountTests extends ESTestCase { handle.remove(); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java index 6420874b83b..704b7dc8871 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/AccountsTests.java @@ -9,16 +9,16 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.secret.SecretService; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class AccountsTests extends ESTestCase { - - @Test public void testSingleAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -33,8 +33,7 @@ public class AccountsTests extends ESTestCase { assertThat(account.name(), equalTo("account1")); } - @Test - public void testSingleAccount_NoExplicitDefault() throws Exception { + public void testSingleAccountNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder(); addAccountSettings("account1", builder); @@ -47,7 +46,6 @@ public class AccountsTests extends ESTestCase { assertThat(account.name(), equalTo("account1")); } - @Test public void testMultipleAccounts() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -66,8 +64,7 @@ public class AccountsTests extends ESTestCase { assertThat(account.name(), equalTo("account1")); } - @Test - public void testMultipleAccounts_NoExplicitDefault() throws Exception { + public void testMultipleAccountsNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); addAccountSettings("account1", builder); @@ -85,28 +82,39 @@ public class AccountsTests extends ESTestCase { assertThat(account.name(), isOneOf("account1", "account2")); } - @Test(expected = SettingsException.class) - public void testMultipleAccounts_UnknownDefault() throws Exception { + public void testMultipleAccountsUnknownDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); addAccountSettings("account1", builder); addAccountSettings("account2", builder); - new Accounts(builder.build(), new SecretService.PlainText(), logger); + try { + new Accounts(builder.build(), new SecretService.PlainText(), logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default email account [unknown]")); + } } - @Test(expected = IllegalStateException.class) public void testNoAccount() throws Exception { Settings.Builder builder = Settings.builder(); Accounts accounts = new Accounts(builder.build(), new SecretService.PlainText(), logger); - accounts.account(null); - fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + try { + accounts.account(null); + fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("cannot find default email account as no accounts have been configured")); + } } - @Test(expected = SettingsException.class) - public void testNoAccount_WithDefaultAccount() throws Exception { + public void testNoAccountWithDefaultAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); - new Accounts(builder.build(), new SecretService.PlainText(), logger); + try { + new Accounts(builder.build(), new SecretService.PlainText(), logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default email account [unknown]")); + } } private void addAccountSettings(String name, Settings.Builder builder) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTemplateTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTemplateTests.java index d3201cd64cd..6de33143416 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTemplateTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTemplateTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.text.TextTemplate; import org.elasticsearch.watcher.support.text.TextTemplateEngine; -import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; @@ -28,9 +27,7 @@ import static org.mockito.Mockito.when; /** */ public class EmailTemplateTests extends ESTestCase { - - @Test - public void testEmailTemplate_Parser_SelfGenerated() throws Exception { + public void testEmailTemplateParserSelfGenerated() throws Exception { TextTemplate from = randomFrom(TextTemplate.inline("from@from.com").build(), null); List addresses = new ArrayList<>(); for( int i = 0; i < randomIntBetween(1, 5); ++i){ diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java index 563e5007eb4..2a7c14644b6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/EmailTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.ArrayList; import java.util.List; @@ -24,9 +23,7 @@ import static org.hamcrest.Matchers.equalTo; /** */ public class EmailTests extends ESTestCase { - - @Test - public void testEmail_Parser_SelfGenerated() throws Exception { + public void testEmailParserSelfGenerated() throws Exception { String id = "test-id"; Email.Address from = randomFrom(new Email.Address("from@from.com"), null); List addresses = new ArrayList<>(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/HtmlSanitizerTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/HtmlSanitizerTests.java index 1b010335a38..ab07a30c19c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/HtmlSanitizerTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/HtmlSanitizerTests.java @@ -7,18 +7,15 @@ package org.elasticsearch.watcher.actions.email.service; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; /** * */ public class HtmlSanitizerTests extends ESTestCase { - - @Test - public void testDefault_WithTemplatePlaceholders() { + public void testDefaultWithTemplatePlaceholders() { String blockTag = randomFrom(HtmlSanitizer.BLOCK_TAGS); while (blockTag.equals("li")) { blockTag = randomFrom(HtmlSanitizer.BLOCK_TAGS); @@ -54,8 +51,7 @@ public class HtmlSanitizerTests extends ESTestCase { } } - @Test - public void testDefault_onclick_Disallowed() { + public void testDefaultOnClickDisallowed() { String badHtml = ""; @@ -64,24 +60,21 @@ public class HtmlSanitizerTests extends ESTestCase { assertThat(sanitizedHtml, equalTo("Click me to display Date and Time.")); } - @Test - public void testDefault_ExternalImage_Disallowed() { + public void testDefaultExternalImageDisallowed() { String html = "This is a bad image"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.EMPTY); String sanitizedHtml = sanitizer.sanitize(html); assertThat(sanitizedHtml, equalTo("This is a bad image")); } - @Test - public void testDefault_EmbeddedImage_Allowed() { + public void testDefault_EmbeddedImageAllowed() { String html = "This is a good image"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.EMPTY); String sanitizedHtml = sanitizer.sanitize(html); assertThat(sanitizedHtml, equalTo(html)); } - @Test - public void testDefault_Tables_Allowed() { + public void testDefaultTablesAllowed() { String html = "" + "" + "" + @@ -112,8 +105,7 @@ public class HtmlSanitizerTests extends ESTestCase { assertThat(sanitizedHtml, equalTo(html)); } - @Test - public void testDefault_Formatting_Allowed() { + public void testDefaultFormattingAllowed() { String html = "" + "

"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.EMPTY); @@ -121,16 +113,14 @@ public class HtmlSanitizerTests extends ESTestCase { assertThat(sanitizedHtml, equalTo(html)); } - @Test - public void testDefault_Scipts_Disallowed() { + public void testDefaultSciptsDisallowed() { String html = "This was a dangerous script"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.EMPTY); String sanitizedHtml = sanitizer.sanitize(html); assertThat(sanitizedHtml, equalTo("This was a dangerous script")); } - @Test - public void testCustom_Disabled() { + public void testCustomDisabled() { String html = "This is a bad image"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.builder() .put("watcher.actions.email.html.sanitization.enabled", false) @@ -139,8 +129,7 @@ public class HtmlSanitizerTests extends ESTestCase { assertThat(sanitizedHtml, equalTo(html)); } - @Test - public void testCustom_AllImage_Allowed() { + public void testCustomAllImageAllowed() { String html = "This is a bad image"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.builder() .put("watcher.actions.email.html.sanitization.allow", "img:all") @@ -149,8 +138,7 @@ public class HtmlSanitizerTests extends ESTestCase { assertThat(sanitizedHtml, equalTo(html)); } - @Test - public void testCustom_Tables_Disallowed() { + public void testCustomTablesDisallowed() { String html = "
caption
cell1cell2
"; HtmlSanitizer sanitizer = new HtmlSanitizer(Settings.builder() .put("watcher.actions.email.html.sanitization.disallow", "_tables") @@ -158,5 +146,4 @@ public class HtmlSanitizerTests extends ESTestCase { String sanitizedHtml = sanitizer.sanitize(html); assertThat(sanitizedHtml, equalTo("cell1cell2")); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java index f4d3ad4a5a0..6dc687c5677 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/email/service/InternalEmailServiceTests.java @@ -15,16 +15,18 @@ import org.elasticsearch.watcher.support.secret.Secret; import org.elasticsearch.watcher.support.secret.SecretService; import org.junit.After; import org.junit.Before; -import org.junit.Test; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * */ public class InternalEmailServiceTests extends ESTestCase { - private InternalEmailService service; private Accounts accounts; @@ -45,7 +47,6 @@ public class InternalEmailServiceTests extends ESTestCase { service.stop(); } - @Test public void testSend() throws Exception { Account account = mock(Account.class); when(account.name()).thenReturn("account1"); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactoryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactoryTests.java index edfe44bc672..4d2082e3e27 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactoryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionFactoryTests.java @@ -19,19 +19,20 @@ import org.elasticsearch.watcher.actions.hipchat.service.HipChatService; import org.elasticsearch.watcher.support.text.TextTemplate; import org.elasticsearch.watcher.support.text.TextTemplateEngine; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.actions.ActionBuilders.hipchatAction; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * */ public class HipChatActionFactoryTests extends ESTestCase { - private HipChatActionFactory factory; private HipChatService hipchatService; @@ -41,9 +42,7 @@ public class HipChatActionFactoryTests extends ESTestCase { factory = new HipChatActionFactory(Settings.EMPTY, mock(TextTemplateEngine.class), hipchatService); } - @Test public void testParseAction() throws Exception { - HipChatAccount account = mock(HipChatAccount.class); when(hipchatService.getAccount("_account1")).thenReturn(account); @@ -58,21 +57,22 @@ public class HipChatActionFactoryTests extends ESTestCase { verify(account, times(1)).validateParsedTemplate("_w1", "_a1", action.message); } - @Test(expected = ElasticsearchParseException.class) - public void testParseAction_UnknownAccount() throws Exception { - + public void testParseActionUnknownAccount() throws Exception { when(hipchatService.getAccount("_unknown")).thenReturn(null); HipChatAction action = hipchatAction("_unknown", "_body").build(); XContentBuilder jsonBuilder = jsonBuilder().value(action); XContentParser parser = JsonXContent.jsonXContent.createParser(jsonBuilder.bytes()); parser.nextToken(); - factory.parseAction("_w1", "_a1", parser); + try { + factory.parseAction("_w1", "_a1", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [hipchat] action [_w1]. unknown hipchat account [_unknown]")); + } } - @Test public void testParser() throws Exception { - XContentBuilder builder = jsonBuilder().startObject(); String accountName = randomAsciiOfLength(10); @@ -133,10 +133,7 @@ public class HipChatActionFactoryTests extends ESTestCase { assertThat(action.message, is(new HipChatMessage.Template(body, rooms, users, from, format, color, notify))); } - - @Test - public void testParser_SelfGenerated() throws Exception { - + public void testParserSelfGenerated() throws Exception { String accountName = randomAsciiOfLength(10); TextTemplate body = TextTemplate.inline("_body").build(); HipChatMessage.Template.Builder templateBuilder = new HipChatMessage.Template.Builder(body); @@ -199,11 +196,15 @@ public class HipChatActionFactoryTests extends ESTestCase { assertThat(parsedAction, is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { XContentBuilder builder = jsonBuilder().startObject().field("unknown_field", "value"); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - HipChatAction.parse("_watch", "_action", parser); + try { + HipChatAction.parse("_watch", "_action", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("failed to parse [hipchat] action [_watch/_action]. unexpected token [VALUE_STRING]")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java index af51cec1751..e39a4d18c35 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/HipChatActionTests.java @@ -28,7 +28,6 @@ import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; -import org.junit.Test; import java.util.Arrays; import java.util.Collections; @@ -50,7 +49,6 @@ import static org.mockito.Mockito.when; * */ public class HipChatActionTests extends ESTestCase { - private HipChatService service; @Before @@ -58,7 +56,6 @@ public class HipChatActionTests extends ESTestCase { service = mock(HipChatService.class); } - @Test public void testExecute() throws Exception { final String accountName = "account1"; @@ -125,9 +122,7 @@ public class HipChatActionTests extends ESTestCase { assertThat(((HipChatAction.Result.Executed) result).sentMessages(), sameInstance(sentMessages)); } - @Test public void testParser() throws Exception { - XContentBuilder builder = jsonBuilder().startObject(); String accountName = randomAsciiOfLength(10); @@ -188,10 +183,7 @@ public class HipChatActionTests extends ESTestCase { assertThat(action.message, is(new HipChatMessage.Template(body, rooms, users, from, format, color, notify))); } - - @Test - public void testParser_SelfGenerated() throws Exception { - + public void testParserSelfGenerated() throws Exception { String accountName = randomAsciiOfLength(10); TextTemplate body = TextTemplate.inline("_body").build(); HipChatMessage.Template.Builder templateBuilder = new HipChatMessage.Template.Builder(body); @@ -254,11 +246,15 @@ public class HipChatActionTests extends ESTestCase { assertThat(parsedAction, is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { XContentBuilder builder = jsonBuilder().startObject().field("unknown_field", "value"); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - HipChatAction.parse("_watch", "_action", parser); + try { + HipChatAction.parse("_watch", "_action", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("failed to parse [hipchat] action [_watch/_action]. unexpected token [VALUE_STRING]")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatAccountsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatAccountsTests.java index 9534e8be11a..544ada45fb3 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatAccountsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatAccountsTests.java @@ -10,16 +10,17 @@ import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.http.HttpClient; import org.junit.Before; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; /** * */ public class HipChatAccountsTests extends ESTestCase { - private HttpClient httpClient; @Before @@ -27,7 +28,6 @@ public class HipChatAccountsTests extends ESTestCase { httpClient = mock(HttpClient.class); } - @Test public void testSingleAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -42,8 +42,7 @@ public class HipChatAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test - public void testSingleAccount_NoExplicitDefault() throws Exception { + public void testSingleAccountNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder(); addAccountSettings("account1", builder); @@ -56,7 +55,6 @@ public class HipChatAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test public void testMultipleAccounts() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -75,8 +73,7 @@ public class HipChatAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test - public void testMultipleAccounts_NoExplicitDefault() throws Exception { + public void testMultipleAccountsNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); addAccountSettings("account1", builder); @@ -94,28 +91,39 @@ public class HipChatAccountsTests extends ESTestCase { assertThat(account.name, isOneOf("account1", "account2")); } - @Test(expected = SettingsException.class) - public void testMultipleAccounts_UnknownDefault() throws Exception { + public void testMultipleAccountsUnknownDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); addAccountSettings("account1", builder); addAccountSettings("account2", builder); - new HipChatAccounts(builder.build(), httpClient, logger); + try { + new HipChatAccounts(builder.build(), httpClient, logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default hipchat account [unknown]")); + } } - @Test(expected = IllegalStateException.class) public void testNoAccount() throws Exception { Settings.Builder builder = Settings.builder(); HipChatAccounts accounts = new HipChatAccounts(builder.build(), httpClient, logger); - accounts.account(null); - fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + try { + accounts.account(null); + fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("cannot find default hipchat account as no accounts have been configured")); + } } - @Test(expected = SettingsException.class) - public void testNoAccount_WithDefaultAccount() throws Exception { + public void testNoAccountWithDefaultAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); - new HipChatAccounts(builder.build(), httpClient, logger); + try { + new HipChatAccounts(builder.build(), httpClient, logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default hipchat account [unknown]")); + } } private void addAccountSettings(String name, Settings.Builder builder) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatMessageTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatMessageTests.java index 594631e51ac..b9c49a52ed8 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatMessageTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatMessageTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.text.TextTemplate; import org.elasticsearch.watcher.support.xcontent.WatcherXContentUtils; -import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -22,14 +21,14 @@ import java.util.List; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class HipChatMessageTests extends ESTestCase { - - @Test public void testToXContent() throws Exception { String message = randomAsciiOfLength(10); String[] rooms = generateRandomStringArray(3, 10, true); @@ -105,7 +104,6 @@ public class HipChatMessageTests extends ESTestCase { assertThat(notify, is(msg.notify)); } - @Test public void testEquals() throws Exception { String message = randomAsciiOfLength(10); String[] rooms = generateRandomStringArray(3, 10, true); @@ -161,8 +159,7 @@ public class HipChatMessageTests extends ESTestCase { assertThat(msg1.equals(msg2), is(equals)); } - @Test - public void testTemplate_Parse() throws Exception { + public void testTemplateParse() throws Exception { XContentBuilder jsonBuilder = jsonBuilder(); jsonBuilder.startObject(); @@ -233,8 +230,7 @@ public class HipChatMessageTests extends ESTestCase { assertThat(template.notify, is(notify)); } - @Test - public void testTemplate_ParseSelfGenerated() throws Exception { + public void testTemplateParseSelfGenerated() throws Exception { TextTemplate body = TextTemplate.inline(randomAsciiOfLength(10)).build(); HipChatMessage.Template.Builder templateBuilder = new HipChatMessage.Template.Builder(body); @@ -287,5 +283,4 @@ public class HipChatMessageTests extends ESTestCase { } return randomFrom(includes); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatServiceTests.java index 5597230bf9e..0b21a6af6a5 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/HipChatServiceTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.watcher.actions.hipchat.HipChatAction; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; @@ -23,7 +22,9 @@ import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondit import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; /** * @@ -31,7 +32,6 @@ import static org.hamcrest.Matchers.*; @Network @TestLogging("watcher.support.http:TRACE") public class HipChatServiceTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; @@ -62,8 +62,7 @@ public class HipChatServiceTests extends AbstractWatcherIntegrationTestCase { .build(); } - @Test - public void testSendMessage_V1Account() throws Exception { + public void testSendMessageV1Account() throws Exception { HipChatService service = getInstanceFromMaster(HipChatService.class); HipChatMessage hipChatMessage = new HipChatMessage( "/code HipChatServiceIT#testSendMessage_V1Account", @@ -86,8 +85,7 @@ public class HipChatServiceTests extends AbstractWatcherIntegrationTestCase { } } - @Test - public void testSendMessage_IntegrationAccount() throws Exception { + public void testSendMessageIntegrationAccount() throws Exception { HipChatService service = getInstanceFromMaster(HipChatService.class); HipChatMessage hipChatMessage = new HipChatMessage( "/code HipChatServiceIT#testSendMessage_IntegrationAccount", @@ -110,8 +108,7 @@ public class HipChatServiceTests extends AbstractWatcherIntegrationTestCase { } } - @Test - public void testSendMessage_UserAccount() throws Exception { + public void testSendMessageUserAccount() throws Exception { HipChatService service = getInstanceFromMaster(HipChatService.class); HipChatMessage hipChatMessage = new HipChatMessage( "/code HipChatServiceIT#testSendMessage_UserAccount", @@ -134,9 +131,7 @@ public class HipChatServiceTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testWatchWithHipChatAction() throws Exception { - HipChatAccount.Profile profile = randomFrom(HipChatAccount.Profile.values()); String account; HipChatAction.Builder actionBuilder; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/IntegrationAccountTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/IntegrationAccountTests.java index f1f633dbd81..86c5c578d6b 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/IntegrationAccountTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/IntegrationAccountTests.java @@ -12,21 +12,25 @@ import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.support.http.*; -import org.junit.Test; +import org.elasticsearch.watcher.support.http.HttpClient; +import org.elasticsearch.watcher.support.http.HttpMethod; +import org.elasticsearch.watcher.support.http.HttpRequest; +import org.elasticsearch.watcher.support.http.HttpResponse; +import org.elasticsearch.watcher.support.http.Scheme; import java.io.IOException; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * */ public class IntegrationAccountTests extends ESTestCase { - - @Test public void testSettings() throws Exception { String accountName = "_name"; @@ -79,29 +83,40 @@ public class IntegrationAccountTests extends ESTestCase { assertThat(account.defaults.notify, is(defaultNotify)); } - @Test(expected = SettingsException.class) - public void testSettings_NoAuthToken() throws Exception { + public void testSettingsNoAuthToken() throws Exception { Settings.Builder sb = Settings.builder(); sb.put(IntegrationAccount.ROOM_SETTING, randomAsciiOfLength(10)); - new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + try { + new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("hipchat account [_name] missing required [auth_token] setting")); + } } - @Test(expected = SettingsException.class) - public void testSettings_WithoutRoom() throws Exception { + public void testSettingsWithoutRoom() throws Exception { Settings.Builder sb = Settings.builder(); sb.put(IntegrationAccount.AUTH_TOKEN_SETTING, randomAsciiOfLength(50)); - new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + try { + new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("missing required [room] setting for [integration] account profile")); + } } - @Test(expected = SettingsException.class) - public void testSettings_WithoutMultipleRooms() throws Exception { + public void testSettingsWithoutMultipleRooms() throws Exception { Settings.Builder sb = Settings.builder(); sb.put(IntegrationAccount.AUTH_TOKEN_SETTING, randomAsciiOfLength(50)); sb.put(IntegrationAccount.ROOM_SETTING, "_r1,_r2"); - new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + try { + new IntegrationAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("[room] setting for [integration] account must only be set with a single value")); + } } - @Test public void testSend() throws Exception { HttpClient httpClient = mock(HttpClient.class); IntegrationAccount account = new IntegrationAccount("_name", Settings.builder() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/InternalHipChatServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/InternalHipChatServiceTests.java index 3647112e5a0..beb3882624a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/InternalHipChatServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/InternalHipChatServiceTests.java @@ -12,16 +12,22 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.shield.WatcherSettingsFilter; import org.elasticsearch.watcher.support.http.HttpClient; import org.junit.Before; -import org.junit.Test; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * */ public class InternalHipChatServiceTests extends ESTestCase { - private HttpClient httpClient; private NodeSettingsService nodeSettingsService; private WatcherSettingsFilter settingsFilter; @@ -33,8 +39,7 @@ public class InternalHipChatServiceTests extends ESTestCase { settingsFilter = mock(WatcherSettingsFilter.class); } - @Test - public void testSingleAccount_V1() throws Exception { + public void testSingleAccountV1() throws Exception { String accountName = randomAsciiOfLength(10); String host = randomBoolean() ? null : "_host"; int port = randomBoolean() ? -1 : randomIntBetween(300, 400); @@ -82,8 +87,7 @@ public class InternalHipChatServiceTests extends ESTestCase { assertThatSettingsFilterWasAdded(); } - @Test - public void testSingleAccount_Integration() throws Exception { + public void testSingleAccountIntegration() throws Exception { String accountName = randomAsciiOfLength(10); String host = randomBoolean() ? null : "_host"; int port = randomBoolean() ? -1 : randomIntBetween(300, 400); @@ -127,18 +131,21 @@ public class InternalHipChatServiceTests extends ESTestCase { assertThatSettingsFilterWasAdded(); } - @Test(expected = SettingsException.class) - public void testSingleAccount_Integration_NoRoomSetting() throws Exception { + public void testSingleAccountIntegrationNoRoomSetting() throws Exception { String accountName = randomAsciiOfLength(10); Settings.Builder settingsBuilder = Settings.builder() .put("watcher.actions.hipchat.service.account." + accountName + ".profile", HipChatAccount.Profile.INTEGRATION.value()) .put("watcher.actions.hipchat.service.account." + accountName + ".auth_token", "_token"); - InternalHipChatService service = new InternalHipChatService(settingsBuilder.build(), httpClient, nodeSettingsService, settingsFilter); - service.start(); + try (InternalHipChatService service = new InternalHipChatService(settingsBuilder.build(), httpClient, nodeSettingsService, + settingsFilter)) { + service.start(); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), containsString("missing required [room] setting for [integration] account profile")); + } } - @Test - public void testSingleAccount_User() throws Exception { + public void testSingleAccountUser() throws Exception { String accountName = randomAsciiOfLength(10); String host = randomBoolean() ? null : "_host"; int port = randomBoolean() ? -1 : randomIntBetween(300, 400); @@ -190,7 +197,6 @@ public class InternalHipChatServiceTests extends ESTestCase { assertThatSettingsFilterWasAdded(); } - @Test public void testMultipleAccounts() throws Exception { HipChatMessage.Color defaultColor = randomBoolean() ? null : randomFrom(HipChatMessage.Color.values()); HipChatMessage.Format defaultFormat = randomBoolean() ? null : randomFrom(HipChatMessage.Format.values()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/UserAccountTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/UserAccountTests.java index 8123e4da9eb..6691b955b02 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/UserAccountTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/UserAccountTests.java @@ -12,21 +12,27 @@ import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.support.http.*; -import org.junit.Test; +import org.elasticsearch.watcher.support.http.HttpClient; +import org.elasticsearch.watcher.support.http.HttpMethod; +import org.elasticsearch.watcher.support.http.HttpRequest; +import org.elasticsearch.watcher.support.http.HttpResponse; +import org.elasticsearch.watcher.support.http.Scheme; import java.io.IOException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * */ public class UserAccountTests extends ESTestCase { - - @Test public void testSettings() throws Exception { String accountName = "_name"; @@ -95,13 +101,16 @@ public class UserAccountTests extends ESTestCase { assertThat(account.defaults.notify, is(defaultNotify)); } - @Test(expected = SettingsException.class) - public void testSettings_NoAuthToken() throws Exception { + public void testSettingsNoAuthToken() throws Exception { Settings.Builder sb = Settings.builder(); - new UserAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + try { + new UserAccount("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("hipchat account [_name] missing required [auth_token] setting")); + } } - @Test public void testSend() throws Exception { HttpClient httpClient = mock(HttpClient.class); UserAccount account = new UserAccount("_name", Settings.builder() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/V1AccountTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/V1AccountTests.java index 18b3813b7b2..177f25204f6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/V1AccountTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/hipchat/service/V1AccountTests.java @@ -9,19 +9,25 @@ import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.watcher.support.http.*; -import org.junit.Test; +import org.elasticsearch.watcher.support.http.HttpClient; +import org.elasticsearch.watcher.support.http.HttpMethod; +import org.elasticsearch.watcher.support.http.HttpRequest; +import org.elasticsearch.watcher.support.http.HttpResponse; +import org.elasticsearch.watcher.support.http.Scheme; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * */ public class V1AccountTests extends ESTestCase { - - @Test public void testSettings() throws Exception { String accountName = "_name"; @@ -86,13 +92,16 @@ public class V1AccountTests extends ESTestCase { assertThat(account.defaults.notify, is(defaultNotify)); } - @Test(expected = SettingsException.class) - public void testSettings_NoAuthToken() throws Exception { + public void testSettingsNoAuthToken() throws Exception { Settings.Builder sb = Settings.builder(); - new V1Account("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + try { + new V1Account("_name", sb.build(), HipChatServer.DEFAULT, mock(HttpClient.class), mock(ESLogger.class)); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("hipchat account [_name] missing required [auth_token] setting")); + } } - @Test public void testSend() throws Exception { HttpClient httpClient = mock(HttpClient.class); V1Account account = new V1Account("_name", Settings.builder() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionIntegrationTests.java index 7a92d9cb2e0..4fedd5b0d8a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionIntegrationTests.java @@ -9,9 +9,8 @@ import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.joda.time.DateTime; import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.watcher.history.HistoryStore; import org.elasticsearch.watcher.support.WatcherDateTimeUtils; @@ -19,8 +18,8 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; +import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; @@ -33,15 +32,15 @@ import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.transform.TransformBuilders.scriptTransform; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; /** * */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class IndexActionIntegrationTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testSimple() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(cron("0/1 * * * * ? 2020"))) @@ -75,8 +74,7 @@ public class IndexActionIntegrationTests extends AbstractWatcherIntegrationTestC assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); } - @Test - public void testSimple_WithDocField() throws Exception { + public void testSimpleWithDocField() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(cron("0/1 * * * * ? 2020"))) .input(simpleInput("foo", "bar")) @@ -112,8 +110,7 @@ public class IndexActionIntegrationTests extends AbstractWatcherIntegrationTestC assertThat(hit.getSource(), hasEntry("foo", (Object) "bar")); } - @Test - public void testSimple_WithDocField_WrongFieldType() throws Exception { + public void testSimpleWithDocFieldWrongFieldType() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(cron("0/1 * * * * ? 2020"))) .input(simpleInput("foo", "bar")) @@ -143,10 +140,9 @@ public class IndexActionIntegrationTests extends AbstractWatcherIntegrationTestC } - @Test public void testIndexAggsBucketsAsDocuments() throws Exception { DateTime now = timeWarped() ? timeWarp().clock().now(DateTimeZone.UTC) : DateTime.now(DateTimeZone.UTC); - long bucketCount = (long) randomIntBetween(2, 5); + long bucketCount = randomIntBetween(2, 5); for (int i = 0; i < bucketCount; i++) { index("idx", "type", jsonBuilder().startObject() .field("timestamp", now.minusDays(i)) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java index 99c71fce880..949d4f1e3fc 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/index/IndexActionTests.java @@ -25,7 +25,6 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource; import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; -import org.junit.Test; import java.util.Arrays; import java.util.Map; @@ -48,7 +47,6 @@ import static org.joda.time.DateTimeZone.UTC; /** */ public class IndexActionTests extends ESIntegTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -63,9 +61,7 @@ public class IndexActionTests extends ESIntegTestCase { .build(); } - @Test - public void testIndexActionExecute_SingleDoc() throws Exception { - + public void testIndexActionExecuteSingleDoc() throws Exception { String timestampField = randomFrom(null, "_timestamp", "@timestamp"); boolean customTimestampField = "@timestamp".equals(timestampField); @@ -119,9 +115,7 @@ public class IndexActionTests extends ESIntegTestCase { assertThat(terms.getBuckets().get(0).getDocCount(), is(1L)); } - @Test - public void testIndexActionExecute_MultiDoc() throws Exception { - + public void testIndexActionExecuteMultiDoc() throws Exception { String timestampField = randomFrom(null, "_timestamp", "@timestamp"); boolean customTimestampField = "@timestamp".equals(timestampField); @@ -187,7 +181,6 @@ public class IndexActionTests extends ESIntegTestCase { } } - @Test public void testParser() throws Exception { String timestampField = randomBoolean() ? "@timestamp" : null; XContentBuilder builder = jsonBuilder(); @@ -217,8 +210,7 @@ public class IndexActionTests extends ESIntegTestCase { assertThat(executable.action().timeout, equalTo(writeTimeout)); } - @Test - public void testParser_Failure() throws Exception { + public void testParserFailure() throws Exception { XContentBuilder builder = jsonBuilder(); boolean useIndex = randomBoolean(); boolean useType = randomBoolean(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java index db45cad786e..1b1e358f026 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/logging/LoggingActionTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.util.HashMap; @@ -33,6 +32,7 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import static org.joda.time.DateTimeZone.UTC; @@ -44,7 +44,6 @@ import static org.mockito.Mockito.when; /** */ public class LoggingActionTests extends ESTestCase { - private ESLogger actionLogger; private LoggingLevel level; private TextTemplateEngine engine; @@ -56,7 +55,6 @@ public class LoggingActionTests extends ESTestCase { engine = mock(TextTemplateEngine.class); } - @Test public void testExecute() throws Exception { final DateTime now = DateTime.now(UTC); @@ -94,7 +92,6 @@ public class LoggingActionTests extends ESTestCase { assertThat(((LoggingAction.Result.Success) result).loggedText(), is(text)); } - @Test public void testParser() throws Exception { Settings settings = Settings.EMPTY; LoggingActionFactory parser = new LoggingActionFactory(settings, engine); @@ -129,8 +126,7 @@ public class LoggingActionTests extends ESTestCase { assertThat(executable.action().text, is(template)); } - @Test - public void testParser_SelfGenerated() throws Exception { + public void testParserSelfGenerated() throws Exception { Settings settings = Settings.EMPTY; LoggingActionFactory parser = new LoggingActionFactory(settings, engine); @@ -150,8 +146,7 @@ public class LoggingActionTests extends ESTestCase { assertThat(parsedAction, equalTo(executable)); } - @Test - public void testParser_Builder() throws Exception { + public void testParserBuilder() throws Exception { Settings settings = Settings.EMPTY; LoggingActionFactory parser = new LoggingActionFactory(settings, engine); @@ -177,8 +172,7 @@ public class LoggingActionTests extends ESTestCase { assertThat(executable.action(), is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Failure() throws Exception { + public void testParserFailure() throws Exception { Settings settings = Settings.EMPTY; LoggingActionFactory parser = new LoggingActionFactory(settings, engine); @@ -188,8 +182,12 @@ public class LoggingActionTests extends ESTestCase { XContentParser xContentParser = JsonXContent.jsonXContent.createParser(builder.bytes()); xContentParser.nextToken(); - // will fail as there's no text - parser.parseExecutable(randomAsciiOfLength(5), randomAsciiOfLength(5), xContentParser); + try { + parser.parseExecutable(randomAsciiOfLength(5), randomAsciiOfLength(5), xContentParser); + fail("Expected failure as there's no text"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("missing required [text] field")); + } } static void verifyLogger(ESLogger logger, LoggingLevel level, String text) { @@ -213,5 +211,4 @@ public class LoggingActionTests extends ESTestCase { fail("unhandled logging level [" + level.name() + "]"); } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionFactoryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionFactoryTests.java index 00efc4d1060..5ef196e5947 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionFactoryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionFactoryTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.watcher.actions.slack; -import com.carrotsearch.randomizedtesting.annotations.Repeat; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -16,7 +15,6 @@ import org.elasticsearch.watcher.actions.slack.service.SlackAccount; import org.elasticsearch.watcher.actions.slack.service.SlackService; import org.elasticsearch.watcher.support.text.TextTemplateEngine; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.actions.ActionBuilders.slackAction; @@ -29,7 +27,6 @@ import static org.mockito.Mockito.when; * */ public class SlackActionFactoryTests extends ESTestCase { - private SlackActionFactory factory; private SlackService service; @@ -39,9 +36,7 @@ public class SlackActionFactoryTests extends ESTestCase { factory = new SlackActionFactory(Settings.EMPTY, mock(TextTemplateEngine.class), service); } - @Test public void testParseAction() throws Exception { - SlackAccount account = mock(SlackAccount.class); when(service.getAccount("_account1")).thenReturn(account); @@ -54,15 +49,18 @@ public class SlackActionFactoryTests extends ESTestCase { assertThat(parsedAction, is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParseAction_UnknownAccount() throws Exception { - + public void testParseActionUnknownAccount() throws Exception { when(service.getAccount("_unknown")).thenReturn(null); SlackAction action = slackAction("_unknown", createRandomTemplate()).build(); XContentBuilder jsonBuilder = jsonBuilder().value(action); XContentParser parser = JsonXContent.jsonXContent.createParser(jsonBuilder.bytes()); parser.nextToken(); - factory.parseAction("_w1", "_a1", parser); + try { + factory.parseAction("_w1", "_a1", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [slack] action [_w1]. unknown slack account [_unknown]")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java index 72d46543344..65572a3aad8 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/SlackActionTests.java @@ -29,7 +29,6 @@ import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; @@ -55,7 +54,6 @@ import static org.mockito.Mockito.when; * */ public class SlackActionTests extends ESTestCase { - private SlackService service; @Before @@ -63,7 +61,6 @@ public class SlackActionTests extends ESTestCase { service = mock(SlackService.class); } - @Test public void testExecute() throws Exception { final String accountName = "account1"; @@ -147,9 +144,7 @@ public class SlackActionTests extends ESTestCase { assertThat(((SlackAction.Result.Executed) result).sentMessages(), sameInstance(sentMessages)); } - @Test public void testParser() throws Exception { - XContentBuilder builder = jsonBuilder().startObject(); String accountName = randomAsciiOfLength(10); @@ -172,10 +167,7 @@ public class SlackActionTests extends ESTestCase { assertThat(action.message, is(message)); } - - @Test - public void testParser_SelfGenerated() throws Exception { - + public void testParserSelfGenerated() throws Exception { String accountName = randomBoolean() ? randomAsciiOfLength(10) : null; SlackMessage.Template message = SlackMessageTests.createRandomTemplate(); @@ -194,11 +186,15 @@ public class SlackActionTests extends ESTestCase { assertThat(parsedAction, is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { XContentBuilder builder = jsonBuilder().startObject().field("unknown_field", "value"); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - SlackAction.parse("_watch", "_action", parser); + try { + SlackAction.parse("_watch", "_action", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("failed to parse [slack] action [_watch/_action]. unexpected token [VALUE_STRING]")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackAccountsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackAccountsTests.java index 95fad4fd5a7..ac9816b56f1 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackAccountsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackAccountsTests.java @@ -11,18 +11,19 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.actions.slack.service.message.SlackMessageDefaultsTests; import org.elasticsearch.watcher.support.http.HttpClient; import org.junit.Before; -import org.junit.Test; import java.util.Map; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; /** * */ public class SlackAccountsTests extends ESTestCase { - private HttpClient httpClient; @Before @@ -30,7 +31,6 @@ public class SlackAccountsTests extends ESTestCase { httpClient = mock(HttpClient.class); } - @Test public void testSingleAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -45,8 +45,7 @@ public class SlackAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test - public void testSingleAccount_NoExplicitDefault() throws Exception { + public void testSingleAccountNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder(); addAccountSettings("account1", builder); @@ -59,7 +58,6 @@ public class SlackAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test public void testMultipleAccounts() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); @@ -78,8 +76,7 @@ public class SlackAccountsTests extends ESTestCase { assertThat(account.name, equalTo("account1")); } - @Test - public void testMultipleAccounts_NoExplicitDefault() throws Exception { + public void testMultipleAccountsNoExplicitDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "account1"); addAccountSettings("account1", builder); @@ -97,28 +94,39 @@ public class SlackAccountsTests extends ESTestCase { assertThat(account.name, isOneOf("account1", "account2")); } - @Test(expected = SettingsException.class) - public void testMultipleAccounts_UnknownDefault() throws Exception { + public void testMultipleAccountsUnknownDefault() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); addAccountSettings("account1", builder); addAccountSettings("account2", builder); - new SlackAccounts(builder.build(), httpClient, logger); + try { + new SlackAccounts(builder.build(), httpClient, logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default slack account [unknown]")); + } } - @Test(expected = IllegalStateException.class) public void testNoAccount() throws Exception { Settings.Builder builder = Settings.builder(); SlackAccounts accounts = new SlackAccounts(builder.build(), httpClient, logger); - accounts.account(null); - fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + try { + accounts.account(null); + fail("no accounts are configured so trying to get the default account should throw an IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("cannot find default slack account as no accounts have been configured")); + } } - @Test(expected = SettingsException.class) - public void testNoAccount_WithDefaultAccount() throws Exception { + public void testNoAccountWithDefaultAccount() throws Exception { Settings.Builder builder = Settings.builder() .put("default_account", "unknown"); - new SlackAccounts(builder.build(), httpClient, logger); + try { + new SlackAccounts(builder.build(), httpClient, logger); + fail("Expected SettingsException"); + } catch (SettingsException e) { + assertThat(e.getMessage(), is("could not find default slack account [unknown]")); + } } private void addAccountSettings(String name, Settings.Builder builder) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackServiceTests.java index fb7dab4bbe3..6c1567f9823 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/SlackServiceTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.watcher.actions.slack.service.message.Attachment; import org.elasticsearch.watcher.actions.slack.service.message.SlackMessage; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; @@ -24,14 +23,15 @@ import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondit import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; /** * */ @Network public class SlackServiceTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; @@ -52,7 +52,6 @@ public class SlackServiceTests extends AbstractWatcherIntegrationTestCase { .build(); } - @Test public void testSendMessage() throws Exception { SlackService service = getInstanceFromMaster(SlackService.class); Attachment[] attachments = new Attachment[] { @@ -76,9 +75,7 @@ public class SlackServiceTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testWatchWithSlackAction() throws Exception { - String account = "test_account"; SlackAction.Builder actionBuilder = slackAction(account, SlackMessage.Template.builder() .setText("slack integration test `{{ctx.payload.ref}}`") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageDefaultsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageDefaultsTests.java index d9a3319a472..eb0ce5d184a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageDefaultsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageDefaultsTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.watcher.actions.slack.service.message; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.hamcrest.Matchers.is; @@ -15,8 +14,6 @@ import static org.hamcrest.Matchers.is; * */ public class SlackMessageDefaultsTests extends ESTestCase { - - @Test public void testConstructor() throws Exception { Settings settings = randomSettings(); SlackMessageDefaults defaults = new SlackMessageDefaults(settings); @@ -102,5 +99,4 @@ public class SlackMessageDefaultsTests extends ESTestCase { } return settings.build(); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageTests.java index 08072d85949..486a4a440c6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/slack/service/message/SlackMessageTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.text.TextTemplate; import org.elasticsearch.watcher.support.text.TextTemplateEngine; -import org.junit.Test; import java.io.IOException; import java.util.ArrayList; @@ -24,14 +23,14 @@ import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; /** * */ public class SlackMessageTests extends ESTestCase { - - @Test public void testToXContent() throws Exception { String from = randomBoolean() ? null : randomAsciiOfLength(10); String[] to = rarely() ? null : new String[randomIntBetween(0, 2)]; @@ -222,9 +221,7 @@ public class SlackMessageTests extends ESTestCase { assertThat(actual, equalTo(expected)); } - - @Test - public void testTemplate_Parse() throws Exception { + public void testTemplateParse() throws Exception { ToXContent.Params params = ToXContent.EMPTY_PARAMS; XContentBuilder jsonBuilder = jsonBuilder(); jsonBuilder.startObject(); @@ -362,8 +359,7 @@ public class SlackMessageTests extends ESTestCase { } } - @Test - public void testTemplate_ParseSelfGenerated() throws Exception { + public void testTemplateParseSelfGenerated() throws Exception { SlackMessage.Template template = createRandomTemplate(); XContentBuilder jsonBuilder = jsonBuilder(); @@ -377,8 +373,7 @@ public class SlackMessageTests extends ESTestCase { assertThat(parsed, equalTo(template)); } - @Test - public void testTemplate_Render() throws Exception { + public void testTemplateRender() throws Exception { Settings settings = SlackMessageDefaultsTests.randomSettings(); SlackMessageDefaults defaults = new SlackMessageDefaults(settings); SlackMessage.Template.Builder templateBuilder = SlackMessage.Template.builder(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/AckThrottlerTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/AckThrottlerTests.java index 3d03a15a0e2..8d51a521252 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/AckThrottlerTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/AckThrottlerTests.java @@ -5,14 +5,13 @@ */ package org.elasticsearch.watcher.actions.throttler; -import org.elasticsearch.watcher.support.clock.SystemClock; -import org.joda.time.DateTime; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.execution.WatchExecutionContext; +import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStatus; -import org.junit.Test; +import org.joda.time.DateTime; import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.formatDate; import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; @@ -26,8 +25,6 @@ import static org.mockito.Mockito.when; * */ public class AckThrottlerTests extends ESTestCase { - - @Test public void testWhenAcked() throws Exception { DateTime timestamp = SystemClock.INSTANCE.nowUTC(); WatchExecutionContext ctx = mockExecutionContext("_watch", EMPTY_PAYLOAD); @@ -43,8 +40,7 @@ public class AckThrottlerTests extends ESTestCase { assertThat(result.reason(), is("action [_action] was acked at [" + formatDate(timestamp) + "]")); } - @Test - public void testThrottle_When_AwaitsSuccessfulExecution() throws Exception { + public void testThrottleWhenAwaitsSuccessfulExecution() throws Exception { DateTime timestamp = SystemClock.INSTANCE.nowUTC(); WatchExecutionContext ctx = mockExecutionContext("_watch", EMPTY_PAYLOAD); Watch watch = ctx.watch(); @@ -59,8 +55,7 @@ public class AckThrottlerTests extends ESTestCase { assertThat(result.reason(), nullValue()); } - @Test - public void testThrottle_When_Ackable() throws Exception { + public void testThrottleWhenAckable() throws Exception { DateTime timestamp = SystemClock.INSTANCE.nowUTC(); WatchExecutionContext ctx = mockExecutionContext("_watch", EMPTY_PAYLOAD); Watch watch = ctx.watch(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/ActionThrottleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/ActionThrottleTests.java index f9aef02612d..725b23429a5 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/ActionThrottleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/ActionThrottleTests.java @@ -34,7 +34,6 @@ import org.elasticsearch.watcher.trigger.schedule.ScheduleTrigger; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.io.IOException; import java.util.HashSet; @@ -51,8 +50,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testSingleActionAckThrottle() throws Exception { boolean useClientForAcking = randomBoolean(); @@ -92,7 +89,6 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testRandomMultiActionAckThrottle() throws Exception { boolean useClientForAcking = randomBoolean(); @@ -140,7 +136,6 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testDifferentThrottlePeriods() throws Exception { WatchSourceBuilder watchSourceBuilder = watchBuilder() .trigger(schedule(interval("60m"))); @@ -190,7 +185,6 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { } - @Test public void testDefaultThrottlePeriod() throws Exception { WatchSourceBuilder watchSourceBuilder = watchBuilder() .trigger(schedule(interval("60m"))); @@ -252,7 +246,6 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { }, 6, TimeUnit.SECONDS); } - @Test public void testWatchThrottlePeriod() throws Exception { WatchSourceBuilder watchSourceBuilder = watchBuilder() .trigger(schedule(interval("60m"))) @@ -314,7 +307,6 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { }, 20, TimeUnit.SECONDS); } - @Test public void testFailingActionDoesGetThrottled() throws Exception { TimeValue throttlePeriod = new TimeValue(60, TimeUnit.MINUTES); @@ -414,10 +406,8 @@ public class ActionThrottleTests extends AbstractWatcherIntegrationTestCase { } }; - public abstract Action.Builder action() throws Exception; public abstract String type(); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/PeriodThrottlerTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/PeriodThrottlerTests.java index ddfd12bde0a..c307b0c6810 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/PeriodThrottlerTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/PeriodThrottlerTests.java @@ -5,20 +5,20 @@ */ package org.elasticsearch.watcher.actions.throttler; -import org.joda.time.DateTime; -import org.joda.time.PeriodType; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.actions.ActionStatus; import org.elasticsearch.watcher.execution.WatchExecutionContext; import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.watch.WatchStatus; -import org.junit.Test; +import org.joda.time.PeriodType; import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -26,9 +26,7 @@ import static org.mockito.Mockito.when; * */ public class PeriodThrottlerTests extends ESTestCase { - - @Test - public void testBelowPeriod_Successful() throws Exception { + public void testBelowPeriodSuccessful() throws Exception { PeriodType periodType = randomFrom(PeriodType.millis(), PeriodType.seconds(), PeriodType.minutes()); TimeValue period = TimeValue.timeValueSeconds(randomIntBetween(2, 5)); PeriodThrottler throttler = new PeriodThrottler(SystemClock.INSTANCE, period, periodType); @@ -47,7 +45,6 @@ public class PeriodThrottlerTests extends ESTestCase { assertThat(result.reason(), startsWith("throttling interval is set to [" + period.format(periodType) + "]")); } - @Test public void testAbovePeriod() throws Exception { PeriodType periodType = randomFrom(PeriodType.millis(), PeriodType.seconds(), PeriodType.minutes()); TimeValue period = TimeValue.timeValueSeconds(randomIntBetween(2, 5)); @@ -65,5 +62,4 @@ public class PeriodThrottlerTests extends ESTestCase { assertThat(result.throttle(), is(false)); assertThat(result.reason(), nullValue()); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/WatchThrottlerTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/WatchThrottlerTests.java index a4b933e3e1b..596630e2f28 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/WatchThrottlerTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/throttler/WatchThrottlerTests.java @@ -8,9 +8,10 @@ package org.elasticsearch.watcher.actions.throttler; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.execution.WatchExecutionContext; import org.elasticsearch.watcher.license.WatcherLicensee; -import org.junit.Test; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -18,9 +19,7 @@ import static org.mockito.Mockito.when; * */ public class WatchThrottlerTests extends ESTestCase { - - @Test - public void testThrottle_DueToAck() throws Exception { + public void testThrottleDueToAck() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); WatchExecutionContext ctx = mock(WatchExecutionContext.class); @@ -35,8 +34,7 @@ public class WatchThrottlerTests extends ESTestCase { assertThat(result, is(expectedResult)); } - @Test - public void testThrottle_DueToPeriod() throws Exception { + public void testThrottleDueToPeriod() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); WatchExecutionContext ctx = mock(WatchExecutionContext.class); @@ -51,8 +49,7 @@ public class WatchThrottlerTests extends ESTestCase { assertThat(result, is(expectedResult)); } - @Test - public void testThrottle_DueAckAndPeriod() throws Exception { + public void testThrottleDueAckAndPeriod() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); WatchExecutionContext ctx = mock(WatchExecutionContext.class); @@ -69,7 +66,6 @@ public class WatchThrottlerTests extends ESTestCase { assertThat(result, is(periodResult)); } - @Test public void testNoThrottle() throws Exception { PeriodThrottler periodThrottler = mock(PeriodThrottler.class); AckThrottler ackThrottler = mock(AckThrottler.class); @@ -84,7 +80,6 @@ public class WatchThrottlerTests extends ESTestCase { assertThat(result, is(Throttler.Result.NO)); } - @Test public void testWithoutPeriod() throws Exception { AckThrottler ackThrottler = mock(AckThrottler.class); WatchExecutionContext ctx = mock(WatchExecutionContext.class); @@ -98,7 +93,6 @@ public class WatchThrottlerTests extends ESTestCase { assertThat(result, sameInstance(ackResult)); } - @Test public void testThatRestrictedLicenseReturnsCorrectResult() throws Exception { AckThrottler ackThrottler = mock(AckThrottler.class); WatchExecutionContext ctx = mock(WatchExecutionContext.class); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java index 7afe2e59ad1..b8462b7d5a9 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookActionTests.java @@ -44,7 +44,6 @@ import org.hamcrest.Matchers; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.util.HashMap; @@ -57,6 +56,7 @@ import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; @@ -73,7 +73,6 @@ import static org.mockito.Mockito.when; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class WebhookActionTests extends ESTestCase { - static final String TEST_HOST = "test.com"; static final int TEST_PORT = 8089; @@ -105,7 +104,6 @@ public class WebhookActionTests extends ESTestCase { tp.shutdownNow(); } - @Test public void testExecute() throws Exception { ExecuteScenario scenario = randomFrom(ExecuteScenario.Success, ExecuteScenario.ErrorCode); @@ -140,7 +138,6 @@ public class WebhookActionTests extends ESTestCase { return builder.build(); } - @Test public void testParser() throws Exception { TextTemplate body = randomBoolean() ? TextTemplate.inline("_subject").build() : null; TextTemplate path = TextTemplate.inline("_url").build(); @@ -161,8 +158,7 @@ public class WebhookActionTests extends ESTestCase { assertThat(executable.action().getRequest(), equalTo(request)); } - @Test - public void testParser_SelfGenerated() throws Exception { + public void testParserSelfGenerated() throws Exception { TextTemplate body = randomBoolean() ? TextTemplate.inline("_body").build() : null; TextTemplate path = TextTemplate.inline("_url").build(); String host = "test.host"; @@ -188,8 +184,7 @@ public class WebhookActionTests extends ESTestCase { assertThat(parsedExecutable.action(), is(action)); } - @Test - public void testParser_Builder() throws Exception { + public void testParserBuilder() throws Exception { TextTemplate body = randomBoolean() ? TextTemplate.inline("_body").build() : null; TextTemplate path = TextTemplate.inline("_url").build(); String host = "test.host"; @@ -213,8 +208,7 @@ public class WebhookActionTests extends ESTestCase { assertThat(parsedAction.action(), is(action)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Failure() throws Exception { + public void testParserFailure() throws Exception { XContentBuilder builder = jsonBuilder().startObject(); if (randomBoolean()) { builder.field(HttpRequest.Field.HOST.getPreferredName(), TEST_HOST); @@ -228,17 +222,19 @@ public class WebhookActionTests extends ESTestCase { WebhookActionFactory actionParser = webhookFactory(ExecuteScenario.Success.client()); //This should fail since we are not supplying a url - actionParser.parseExecutable("_watch", randomAsciiOfLength(5), parser); - fail("expected a WebhookActionException since we only provided either a host or a port but not both"); + try { + actionParser.parseExecutable("_watch", randomAsciiOfLength(5), parser); + fail("expected a WebhookActionException since we only provided either a host or a port but not both"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("could not parse http request template. missing required [")); + } } private WebhookActionFactory webhookFactory(HttpClient client) { return new WebhookActionFactory(Settings.EMPTY, client, new HttpRequestTemplate.Parser(authRegistry), templateEngine); } - @Test - public void testTemplatedHttpRequest() throws Exception - { + public void testTemplatedHttpRequest() throws Exception { HttpClient httpClient = ExecuteScenario.Success.client(); String body = "{{ctx.watch_id}}"; @@ -271,9 +267,7 @@ public class WebhookActionTests extends ESTestCase { } - @Test public void testValidUrls() throws Exception { - HttpClient httpClient = ExecuteScenario.Success.client(); HttpMethod method = HttpMethod.POST; TextTemplate path = TextTemplate.defaultType("/test_{{ctx.watch_id}}").build(); @@ -309,7 +303,6 @@ public class WebhookActionTests extends ESTestCase { logger); } - private enum ExecuteScenario { ErrorCode() { @Override @@ -385,5 +378,4 @@ public class WebhookActionTests extends ESTestCase { public abstract void assertResult(HttpClient client, Action.Result result) throws Exception ; } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookHttpsIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookHttpsIntegrationTests.java index 97dbfd6dfd1..6aadfa73483 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookHttpsIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookHttpsIntegrationTests.java @@ -9,6 +9,7 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.QueueDispatcher; import com.squareup.okhttp.mockwebserver.RecordedRequest; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; @@ -26,7 +27,6 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.net.BindException; import java.nio.file.Path; @@ -43,7 +43,6 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; public class WebhookHttpsIntegrationTests extends AbstractWatcherIntegrationTestCase { - private int webPort; private MockWebServer webServer; @@ -81,7 +80,6 @@ public class WebhookHttpsIntegrationTests extends AbstractWatcherIntegrationTest webServer.shutdown(); } - @Test public void testHttps() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequestTemplate.Builder builder = HttpRequestTemplate.builder("localhost", webPort) @@ -124,7 +122,6 @@ public class WebhookHttpsIntegrationTests extends AbstractWatcherIntegrationTest assertThat(status.intValue(), is(200)); } - @Test public void testHttpsAndBasicAuth() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequestTemplate.Builder builder = HttpRequestTemplate.builder("localhost", webPort) @@ -152,5 +149,4 @@ public class WebhookHttpsIntegrationTests extends AbstractWatcherIntegrationTest assertThat(recordedRequest.getBody().readUtf8Line(), equalTo("{key=value}")); assertThat(recordedRequest.getHeader("Authorization"), equalTo("Basic X3VzZXJuYW1lOl9wYXNzd29yZA==")); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookIntegrationTests.java index 9f700a33630..4543b658ff6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/actions/webhook/WebhookIntegrationTests.java @@ -10,6 +10,7 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.QueueDispatcher; import com.squareup.okhttp.mockwebserver.RecordedRequest; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; @@ -24,7 +25,6 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.net.BindException; @@ -35,12 +35,14 @@ import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.test.WatcherTestUtils.xContentSource; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** */ public class WebhookIntegrationTests extends AbstractWatcherIntegrationTestCase { - private int webPort; private MockWebServer webServer; @@ -66,7 +68,6 @@ public class WebhookIntegrationTests extends AbstractWatcherIntegrationTestCase webServer.shutdown(); } - @Test public void testWebhook() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequestTemplate.Builder builder = HttpRequestTemplate.builder("localhost", webPort) @@ -110,7 +111,6 @@ public class WebhookIntegrationTests extends AbstractWatcherIntegrationTestCase assertThat(status.intValue(), is(200)); } - @Test public void testWebhookWithBasicAuth() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequestTemplate.Builder builder = HttpRequestTemplate.builder("localhost", webPort) @@ -139,5 +139,4 @@ public class WebhookIntegrationTests extends AbstractWatcherIntegrationTestCase assertThat(recordedRequest.getBody().readUtf8Line(), equalTo("{key=value}")); assertThat(recordedRequest.getHeader("Authorization"), equalTo("Basic X3VzZXJuYW1lOl9wYXNzd29yZA==")); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/always/AlwaysConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/always/AlwaysConditionTests.java index 3fd57bdf696..02c9e230403 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/always/AlwaysConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/always/AlwaysConditionTests.java @@ -13,22 +13,19 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.condition.ConditionFactory; import org.elasticsearch.watcher.condition.ExecutableCondition; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.hamcrest.Matchers.containsString; /** */ public class AlwaysConditionTests extends ESTestCase { - - @Test public void testExecute() throws Exception { ExecutableCondition alwaysTrue = new ExecutableAlwaysCondition(logger); assertTrue(alwaysTrue.execute(null).met()); } - @Test - public void testParser_Valid() throws Exception { + public void testParserValid() throws Exception { AlwaysConditionFactory factory = new AlwaysConditionFactory(Settings.settingsBuilder().build()); XContentBuilder builder = jsonBuilder(); builder.startObject(); @@ -40,8 +37,7 @@ public class AlwaysConditionTests extends ESTestCase { assertTrue(executable.execute(null).met()); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { ConditionFactory factor = new AlwaysConditionFactory(Settings.settingsBuilder().build()); XContentBuilder builder = jsonBuilder() .startObject() @@ -49,9 +45,12 @@ public class AlwaysConditionTests extends ESTestCase { .endObject(); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); - factor.parseCondition("_id", parser); - fail("expected a condition exception trying to parse an invalid condition XContent, [" - + AlwaysCondition.TYPE + "] condition should not parse with a body"); + try { + factor.parseCondition("_id", parser); + fail("expected a condition exception trying to parse an invalid condition XContent, [" + + AlwaysCondition.TYPE + "] condition should not parse with a body"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected an empty object but found [foo]")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionSearchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionSearchTests.java index 2577266415b..3be082796ec 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionSearchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionSearchTests.java @@ -19,21 +19,19 @@ import org.elasticsearch.watcher.execution.WatchExecutionContext; import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.watch.Payload; -import org.junit.Test; import java.util.Map; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.when; /** */ public class CompareConditionSearchTests extends AbstractWatcherIntegrationTestCase { - - @Test - public void testExecute_withAggs() throws Exception { - + public void testExecuteWithAggs() throws Exception { client().admin().indices().prepareCreate("my-index") .addMapping("my-type", "_timestamp", "enabled=true") .get(); @@ -73,8 +71,7 @@ public class CompareConditionSearchTests extends AbstractWatcherIntegrationTestC assertThat(resolvedValues, hasEntry("ctx.payload.aggregations.rate.buckets.0.doc_count", (Object) 5)); } - @Test - public void testExecute_accessHits() throws Exception { + public void testExecuteAccessHits() throws Exception { ExecutableCompareCondition condition = new ExecutableCompareCondition(new CompareCondition("ctx.payload.hits.hits.0._score", CompareCondition.Op.EQ, 1), logger, SystemClock.INSTANCE); InternalSearchHit hit = new InternalSearchHit(0, "1", new StringText("type"), null); hit.score(1f); @@ -94,5 +91,4 @@ public class CompareConditionSearchTests extends AbstractWatcherIntegrationTestC assertThat(resolvedValues.size(), is(1)); assertThat(resolvedValues, hasEntry(is("ctx.payload.hits.hits.0._score"), notNullValue())); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java index 66b1e791ecd..6bd6b4d4f05 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/CompareConditionTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.watcher.support.clock.ClockMock; import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; -import org.junit.Test; import java.util.Arrays; import java.util.Locale; @@ -25,15 +24,14 @@ import java.util.Locale; import static java.util.Collections.singletonMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /** */ public class CompareConditionTests extends ESTestCase { - - @Test - public void testOpEval_EQ() throws Exception { + public void testOpEvalEQ() throws Exception { assertThat(Op.EQ.eval(null, null), is(true)); assertThat(Op.EQ.eval(4, 3.0), is(false)); assertThat(Op.EQ.eval(3, 3.0), is(true)); @@ -52,8 +50,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k1", "v1")), is(false)); } - @Test - public void testOpEval_NOT_EQ() throws Exception { + public void testOpEvalNotEQ() throws Exception { assertThat(Op.NOT_EQ.eval(null, null), is(false)); assertThat(Op.NOT_EQ.eval(4, 3.0), is(true)); assertThat(Op.NOT_EQ.eval(3, 3.0), is(false)); @@ -72,8 +69,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.NOT_EQ.eval(Arrays.asList("k", "v"), Arrays.asList("k1", "v1")), is(true)); } - @Test - public void testOpEval_GTE() throws Exception { + public void testOpEvalGTE() throws Exception { assertThat(Op.GTE.eval(4, 3.0), is(true)); assertThat(Op.GTE.eval(3, 3.0), is(true)); assertThat(Op.GTE.eval(2, new Float(3.0)), is(false)); @@ -87,8 +83,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.GTE.eval("aa", "ab"), is(false)); } - @Test - public void testOpEval_GT() throws Exception { + public void testOpEvalGT() throws Exception { assertThat(Op.GT.eval(4, 3.0), is(true)); assertThat(Op.GT.eval(3, 3.0), is(false)); assertThat(Op.GT.eval(2, new Float(3.0)), is(false)); @@ -102,8 +97,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.GT.eval("aa", "ab"), is(false)); } - @Test - public void testOpEval_LTE() throws Exception { + public void testOpEvalLTE() throws Exception { assertThat(Op.LTE.eval(4, 3.0), is(false)); assertThat(Op.LTE.eval(3, 3.0), is(true)); assertThat(Op.LTE.eval(2, new Float(3.0)), is(true)); @@ -117,8 +111,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.LTE.eval("aa", "ab"), is(true)); } - @Test - public void testOpEval_LT() throws Exception { + public void testOpEvalLT() throws Exception { assertThat(Op.LT.eval(4, 3.0), is(false)); assertThat(Op.LT.eval(3, 3.0), is(false)); assertThat(Op.LT.eval(2, new Float(3.0)), is(true)); @@ -132,7 +125,6 @@ public class CompareConditionTests extends ESTestCase { assertThat(Op.LT.eval("aa", "ab"), is(true)); } - @Test public void testExecute() throws Exception { Op op = randomFrom(Op.values()); int value = randomInt(10); @@ -144,8 +136,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - @Test - public void testExecute_DateMath() throws Exception { + public void testExecuteDateMath() throws Exception { ClockMock clock = new ClockMock(); boolean met = randomBoolean(); Op op = met ? randomFrom(Op.GT, Op.GTE, Op.NOT_EQ) : randomFrom(Op.LT, Op.LTE, Op.EQ); @@ -157,8 +148,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - @Test - public void testExecute_Path() throws Exception { + public void testExecutePath() throws Exception { ClockMock clock = new ClockMock(); boolean met = randomBoolean(); Op op = met ? Op.EQ : Op.NOT_EQ; @@ -170,9 +160,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - - @Test - public void testParse_Valid() throws Exception { + public void testParseValid() throws Exception { Op op = randomFrom(Op.values()); Object value = randomFrom("value", 1, null); CompareConditionFactory factory = new CompareConditionFactory(Settings.EMPTY, SystemClock.INSTANCE); @@ -194,8 +182,7 @@ public class CompareConditionTests extends ESTestCase { assertThat(condition.getValue(), is(value)); } - @Test(expected = ElasticsearchParseException.class) - public void testParse_InValid_NoOperationBody() throws Exception { + public void testParseInvalidNoOperationBody() throws Exception { CompareConditionFactory factory = new CompareConditionFactory(Settings.EMPTY, SystemClock.INSTANCE); XContentBuilder builder = jsonBuilder(); builder.startObject(); @@ -204,11 +191,15 @@ public class CompareConditionTests extends ESTestCase { builder.endObject(); XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); - factory.parseCondition("_id", parser); + try { + factory.parseCondition("_id", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected an object but found [null] instead")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_InValid_UnknownOp() throws Exception { + public void testParseInvalidUnknownOp() throws Exception { Object value = randomFrom("value", 1, null); CompareConditionFactory factory = new CompareConditionFactory(Settings.EMPTY, SystemClock.INSTANCE); XContentBuilder builder = jsonBuilder(); @@ -220,12 +211,15 @@ public class CompareConditionTests extends ESTestCase { XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - - factory.parseCondition("_id", parser); + try { + factory.parseCondition("_id", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("unknown comparison operator [foobar]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_InValid_WrongValueForOp() throws Exception { + public void testParseInvalidWrongValueForOp() throws Exception { Object value = randomFrom(Arrays.asList("1", "2"), singletonMap("key", "value")); String op = randomFrom("lt", "lte", "gt", "gte"); CompareConditionFactory factory = new CompareConditionFactory(Settings.EMPTY, SystemClock.INSTANCE); @@ -238,8 +232,11 @@ public class CompareConditionTests extends ESTestCase { XContentParser parser = JsonXContent.jsonXContent.createParser(builder.bytes()); parser.nextToken(); - - factory.parseCondition("_id", parser); + try { + factory.parseCondition("_id", parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("must either be a numeric, string, boolean or null value, but found [")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionSearchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionSearchTests.java index dcc134fb6e1..960aeb21663 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionSearchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionSearchTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.watcher.execution.WatchExecutionContext; import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.watch.Payload; -import org.junit.Test; import java.io.IOException; import java.util.Arrays; @@ -26,8 +25,6 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.collection.IsMapContaining.hasEntry; public class ArrayCompareConditionSearchTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testExecuteWithAggs() throws Exception { String index = "test-index"; String type = "test-type"; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionTests.java index 03bf6f1e5eb..7eb1aa8fae6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/compare/array/ArrayCompareConditionTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.watcher.support.clock.ClockMock; import org.elasticsearch.watcher.support.clock.SystemClock; import org.elasticsearch.watcher.watch.Payload; import org.junit.Rule; -import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; @@ -33,11 +32,9 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.is; public class ArrayCompareConditionTests extends ESTestCase { - @Rule public ExpectedException expectedException = ExpectedException.none(); - @Test public void testOpEvalEQ() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 1), 1, ArrayCompareCondition.Op.EQ), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 2, ArrayCompareCondition.Op.EQ), is(false)); @@ -47,8 +44,7 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.EQ), is(false)); } - @Test - public void testOpEvalNOT_EQ() throws Exception { + public void testOpEvalNotEQ() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 1), 3, ArrayCompareCondition.Op.NOT_EQ), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 1, ArrayCompareCondition.Op.NOT_EQ), is(false)); assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Arrays.asList(1, 3), 1, ArrayCompareCondition.Op.NOT_EQ), is(true)); @@ -57,7 +53,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.NOT_EQ), is(false)); } - @Test public void testOpEvalGTE() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 1, ArrayCompareCondition.Op.GTE), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 2, ArrayCompareCondition.Op.GTE), is(false)); @@ -67,7 +62,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.GTE), is(false)); } - @Test public void testOpEvalGT() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 0, ArrayCompareCondition.Op.GT), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 1, ArrayCompareCondition.Op.GT), is(false)); @@ -77,7 +71,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.GT), is(false)); } - @Test public void testOpEvalLTE() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 3, ArrayCompareCondition.Op.LTE), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 0, ArrayCompareCondition.Op.LTE), is(false)); @@ -87,7 +80,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.LTE), is(false)); } - @Test public void testOpEvalLT() throws Exception { assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 4, ArrayCompareCondition.Op.LT), is(true)); assertThat(ArrayCompareCondition.Quantifier.ALL.eval(Arrays.asList(1, 3), 3, ArrayCompareCondition.Op.LT), is(false)); @@ -97,7 +89,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(ArrayCompareCondition.Quantifier.SOME.eval(Collections.emptyList(), 1, ArrayCompareCondition.Op.LT), is(false)); } - @Test public void testExecute() { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); int value = randomInt(10); @@ -121,7 +112,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - @Test public void testExecutePath() { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); int value = randomInt(10); @@ -151,7 +141,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - @Test public void testExecuteDateMath() { ClockMock clock = new ClockMock(); boolean met = randomBoolean(); @@ -170,7 +159,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(condition.execute(ctx).met(), is(met)); } - @Test public void testParse() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); @@ -200,7 +188,6 @@ public class ArrayCompareConditionTests extends ESTestCase { assertThat(condition.getQuantifier(), is(quantifier)); } - @Test public void testParseContainsDuplicateOperator() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); @@ -230,7 +217,6 @@ public class ArrayCompareConditionTests extends ESTestCase { factory.parseCondition("_id", parser); } - @Test public void testParseContainsUnknownOperator() throws IOException { ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); Object value = randomFrom("value", 1, null); @@ -255,7 +241,6 @@ public class ArrayCompareConditionTests extends ESTestCase { factory.parseCondition("_id", parser); } - @Test public void testParseContainsDuplicateValue() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); @@ -282,7 +267,6 @@ public class ArrayCompareConditionTests extends ESTestCase { factory.parseCondition("_id", parser); } - @Test public void testParseContainsDuplicateQuantifier() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); @@ -309,7 +293,6 @@ public class ArrayCompareConditionTests extends ESTestCase { factory.parseCondition("_id", parser); } - @Test public void testParseContainsUnknownQuantifier() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); Object value = randomFrom("value", 1, null); @@ -334,7 +317,6 @@ public class ArrayCompareConditionTests extends ESTestCase { factory.parseCondition("_id", parser); } - @Test public void testParseContainsUnexpectedFieldInComparisonOperator() throws IOException { ArrayCompareCondition.Op op = randomFrom(ArrayCompareCondition.Op.values()); ArrayCompareCondition.Quantifier quantifier = randomFrom(ArrayCompareCondition.Quantifier.values()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/never/NeverConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/never/NeverConditionTests.java index 9d2ac153e52..98313213242 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/never/NeverConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/never/NeverConditionTests.java @@ -14,22 +14,19 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.condition.ConditionFactory; import org.elasticsearch.watcher.condition.ExecutableCondition; import org.elasticsearch.watcher.condition.always.AlwaysCondition; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.hamcrest.Matchers.containsString; /** */ public class NeverConditionTests extends ESTestCase { - - @Test public void testExecute() throws Exception { ExecutableCondition executable = new ExecutableNeverCondition(logger); assertFalse(executable.execute(null).met()); } - @Test - public void testParser_Valid() throws Exception { + public void testParserValid() throws Exception { NeverConditionFactory factory = new NeverConditionFactory(Settings.settingsBuilder().build()); XContentBuilder builder = jsonBuilder(); builder.startObject(); @@ -42,8 +39,7 @@ public class NeverConditionTests extends ESTestCase { assertFalse(executable.execute(null).met()); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { + public void testParserInvalid() throws Exception { ConditionFactory factory = new NeverConditionFactory(Settings.settingsBuilder().build()); XContentBuilder builder = jsonBuilder(); builder.startObject(); @@ -51,10 +47,12 @@ public class NeverConditionTests extends ESTestCase { builder.endObject(); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); - - factory.parseCondition("_id", parser); - fail("expected a condition exception trying to parse an invalid condition XContent, [" - + AlwaysCondition.TYPE + "] condition should not parse with a body"); + try { + factory.parseCondition("_id", parser); + fail("expected a condition exception trying to parse an invalid condition XContent, [" + + AlwaysCondition.TYPE + "] condition should not parse with a body"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected an empty object but found [foo]")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java index 4541bd076b0..168796ec327 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionSearchTests.java @@ -25,7 +25,6 @@ import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.watch.Payload; import org.junit.After; import org.junit.Before; -import org.junit.Test; import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; import static org.hamcrest.Matchers.is; @@ -35,7 +34,6 @@ import static org.mockito.Mockito.when; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCase { - private ThreadPool tp = null; private ScriptServiceProxy scriptService; @@ -50,9 +48,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa tp.shutdownNow(); } - @Test - public void testExecute_withAggs() throws Exception { - + public void testExecuteWithAggs() throws Exception { client().admin().indices().prepareCreate("my-index") .addMapping("my-type", "_timestamp", "enabled=true") .get(); @@ -83,8 +79,7 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa assertThat(condition.execute(ctx).met(), is(true)); } - @Test - public void testExecute_accessHits() throws Exception { + public void testExecuteAccessHits() throws Exception { ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(Script.inline("ctx.payload.hits?.hits[0]?._score == 1.0").build()), logger, scriptService); InternalSearchHit hit = new InternalSearchHit(0, "1", new StringText("type"), null); hit.score(1f); @@ -99,5 +94,4 @@ public class ScriptConditionSearchTests extends AbstractWatcherIntegrationTestCa when(ctx.payload()).thenReturn(new Payload.XContent(response)); assertThat(condition.execute(ctx).met(), is(false)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java index fc5cac97511..f66a3de6ce2 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/condition/script/ScriptConditionTests.java @@ -29,7 +29,6 @@ import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.IOException; @@ -46,7 +45,6 @@ import static org.hamcrest.Matchers.notNullValue; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class ScriptConditionTests extends ESTestCase { - ThreadPool tp = null; @Before @@ -59,8 +57,6 @@ public class ScriptConditionTests extends ESTestCase { tp.shutdownNow(); } - - @Test public void testExecute() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(Script.inline("ctx.payload.hits.total > 1").build()), logger, scriptService); @@ -69,8 +65,7 @@ public class ScriptConditionTests extends ESTestCase { assertFalse(condition.execute(ctx).met()); } - @Test - public void testExecute_MergedParams() throws Exception { + public void testExecuteMergedParams() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); Script script = Script.inline("ctx.payload.hits.total > threshold").lang(ScriptService.DEFAULT_LANG).params(singletonMap("threshold", 1)).build(); ExecutableScriptCondition executable = new ExecutableScriptCondition(new ScriptCondition(script), logger, scriptService); @@ -79,8 +74,7 @@ public class ScriptConditionTests extends ESTestCase { assertFalse(executable.execute(ctx).met()); } - @Test - public void testParser_Valid() throws Exception { + public void testParserValid() throws Exception { ScriptConditionFactory factory = new ScriptConditionFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); XContentBuilder builder = createConditionContent("ctx.payload.hits.total > 1", null, ScriptType.INLINE); @@ -107,19 +101,22 @@ public class ScriptConditionTests extends ESTestCase { assertTrue(executable.execute(ctx).met()); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_InValid() throws Exception { + public void testParserInvalid() throws Exception { ScriptConditionFactory factory = new ScriptConditionFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject().endObject(); XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); - factory.parseCondition("_id", parser); - fail("expected a condition exception trying to parse an invalid condition XContent"); + try { + factory.parseCondition("_id", parser); + fail("expected a condition exception trying to parse an invalid condition XContent"); + } catch (ElasticsearchParseException e) { + // TODO add these when the test if fixed + // assertThat(e.getMessage(), is("ASDF")); + } } - @Test(expected = ScriptException.class) - public void testScriptConditionParser_badScript() throws Exception { + public void testScriptConditionParserBadScript() throws Exception { ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); ScriptType scriptType = randomFrom(ScriptType.values()); String script; @@ -136,11 +133,15 @@ public class ScriptConditionTests extends ESTestCase { XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser); - conditionParser.createExecutable(scriptCondition); - fail("expected a condition validation exception trying to create an executable with a bad or missing script"); + try { + conditionParser.createExecutable(scriptCondition); + fail("expected a condition validation exception trying to create an executable with a bad or missing script"); + } catch (ScriptException e) { + // TODO add these when the test if fixed + // assertThat(e.getMessage(), is("ASDF")); + } } - @Test(expected = ScriptException.class) public void testScriptConditionParser_badLang() throws Exception { ScriptConditionFactory conditionParser = new ScriptConditionFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); ScriptType scriptType = ScriptType.INLINE; @@ -149,11 +150,16 @@ public class ScriptConditionTests extends ESTestCase { XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptCondition scriptCondition = conditionParser.parseCondition("_watch", parser); - conditionParser.createExecutable(scriptCondition); - fail("expected a condition validation exception trying to create an executable with an invalid language"); + try { + conditionParser.createExecutable(scriptCondition); + fail("expected a condition validation exception trying to create an executable with an invalid language"); + } catch (ScriptException e) { + // TODO add these when the test if fixed + // assertThat(e.getMessage(), is("ASDF")); + } } - public void testScriptCondition_throwException() throws Exception { + public void testScriptConditionThrowException() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(Script.inline("assert false").build()), logger, scriptService); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); @@ -165,7 +171,7 @@ public class ScriptConditionTests extends ESTestCase { assertThat(result.reason(), containsString("Assertion")); } - public void testScriptCondition_returnObject() throws Exception { + public void testScriptConditionReturnObject() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(Script.inline("return new Object()").build()), logger, scriptService); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); @@ -177,8 +183,7 @@ public class ScriptConditionTests extends ESTestCase { assertThat(result.reason(), containsString("ScriptException")); } - @Test - public void testScriptCondition_accessCtx() throws Exception { + public void testScriptConditionAccessCtx() throws Exception { ScriptServiceProxy scriptService = getScriptServiceProxy(tp); ExecutableScriptCondition condition = new ExecutableScriptCondition(new ScriptCondition(Script.inline("ctx.trigger.scheduled_time.getMillis() < System.currentTimeMillis() ").build()), logger, scriptService); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 500l, new ShardSearchFailure[0]); @@ -211,5 +216,4 @@ public class ScriptConditionTests extends ESTestCase { } return builder.endObject(); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java index b537164df7b..22af250bc98 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/ExecutionServiceTests.java @@ -29,7 +29,6 @@ import org.elasticsearch.watcher.watch.*; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -44,7 +43,6 @@ import static org.mockito.Mockito.*; /** */ public class ExecutionServiceTests extends ESTestCase { - private Payload payload; private ExecutableInput input; private Input.Result inputResult; @@ -82,7 +80,6 @@ public class ExecutionServiceTests extends ESTestCase { executionService.start(clusterState); } - @Test public void testExecute() throws Exception { WatchLockService.Lock lock = mock(WatchLockService.Lock.class); when(watchLockService.acquire("_id")).thenReturn(lock); @@ -151,8 +148,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, times(1)).execute("_action", context, payload); } - @Test - public void testExecute_FailedInput() throws Exception { + public void testExecuteFailedInput() throws Exception { WatchLockService.Lock lock = mock(WatchLockService.Lock.class); when(watchLockService.acquire("_id")).thenReturn(lock); @@ -224,8 +220,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, never()).execute("_action", context, payload); } - @Test - public void testExecute_FailedCondition() throws Exception { + public void testExecuteFailedCondition() throws Exception { WatchLockService.Lock lock = mock(WatchLockService.Lock.class); when(watchLockService.acquire("_id")).thenReturn(lock); @@ -293,8 +288,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, never()).execute("_action", context, payload); } - @Test - public void testExecute_FailedWatchTransform() throws Exception { + public void testExecuteFailedWatchTransform() throws Exception { WatchLockService.Lock lock = mock(WatchLockService.Lock.class); when(watchLockService.acquire("_id")).thenReturn(lock); @@ -361,8 +355,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, never()).execute("_action", context, payload); } - @Test - public void testExecute_FailedActionTransform() throws Exception { + public void testExecuteFailedActionTransform() throws Exception { WatchLockService.Lock lock = mock(WatchLockService.Lock.class); when(watchLockService.acquire("_id")).thenReturn(lock); @@ -434,7 +427,6 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, never()).execute("_action", context, payload); } - @Test public void testExecuteInner() throws Exception { DateTime now = DateTime.now(DateTimeZone.UTC); Watch watch = mock(Watch.class); @@ -495,8 +487,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(action, times(1)).execute("_action", context, payload); } - @Test - public void testExecuteInner_throttled() throws Exception { + public void testExecuteInnerThrottled() throws Exception { DateTime now = DateTime.now(DateTimeZone.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); @@ -544,8 +535,7 @@ public class ExecutionServiceTests extends ESTestCase { verify(transform, never()).execute(context, payload); } - @Test - public void testExecuteInner_conditionNotMet() throws Exception { + public void testExecuteInnerConditionNotMet() throws Exception { DateTime now = DateTime.now(DateTimeZone.UTC); Watch watch = mock(Watch.class); ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/ManualExecutionTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/ManualExecutionTests.java index fa1c90d3f2e..f56297f9f31 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/ManualExecutionTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/ManualExecutionTests.java @@ -38,7 +38,6 @@ import org.elasticsearch.watcher.watch.Payload; import org.elasticsearch.watcher.watch.Watch; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; @@ -69,13 +68,11 @@ import static org.hamcrest.Matchers.startsWith; @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean enableShield() { return false; } - @Test public void testExecuteWatch() throws Exception { boolean ignoreCondition = randomBoolean(); boolean recordExecution = randomBoolean(); @@ -160,7 +157,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testExecutionWithInlineWatch() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) @@ -184,8 +180,7 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { assertThat(executeWatchResponse.getRecordSource().getValue("trigger_event.type").toString(), equalTo("manual")); } - @Test - public void testExecutionWithInlineWatch_withRecordExecutionEnabled() throws Exception { + public void testExecutionWithInlineWatchWithRecordExecutionEnabled() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) .input(simpleInput("foo", "bar")) @@ -204,7 +199,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testExecutionWithInlineWatch_withWatchId() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) @@ -225,7 +219,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testDifferentAlternativeInputs() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) @@ -263,7 +256,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { assertThat(watchRecord2.result().inputResult().payload().data().get("foo"), instanceOf(Map.class)); } - @Test public void testExecutionRequestDefaults() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) @@ -312,7 +304,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { assertThat(ObjectPath.eval("state", executeWatchResult), equalTo(ExecutionState.THROTTLED.toString())); } - @Test public void testWatchExecutionDuration() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) @@ -326,7 +317,6 @@ public class ManualExecutionTests extends AbstractWatcherIntegrationTestCase { assertThat(record.result().executionDurationMs(), greaterThanOrEqualTo(100L)); } - @Test public void testForceDeletionOfLongRunningWatch() throws Exception { WatchSourceBuilder watchBuilder = watchBuilder() .trigger(schedule(cron("0 0 0 1 * ? 2099"))) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreLifeCycleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreLifeCycleTests.java index 433018e2e45..1853a2f25e5 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreLifeCycleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreLifeCycleTests.java @@ -7,25 +7,25 @@ package org.elasticsearch.watcher.execution; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.cluster.ClusterService; -import org.joda.time.DateTime; import org.elasticsearch.watcher.condition.ExecutableCondition; import org.elasticsearch.watcher.condition.always.ExecutableAlwaysCondition; import org.elasticsearch.watcher.input.none.ExecutableNoneInput; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.Watch; +import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.Collection; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** */ public class TriggeredWatchStoreLifeCycleTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testPutLoadUpdate() throws Exception { ExecutableCondition condition = new ExecutableAlwaysCondition(logger); TriggeredWatchStore triggeredWatchStore = getInstanceFromMaster(TriggeredWatchStore.class); @@ -66,5 +66,4 @@ public class TriggeredWatchStoreLifeCycleTests extends AbstractWatcherIntegratio assertThat(loadedTriggeredWatches, notNullValue()); assertThat(loadedTriggeredWatches, hasSize(0)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java index f8932e2381b..cb542d8f235 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchStoreTests.java @@ -35,7 +35,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.hamcrest.core.IsNull; import org.junit.Before; -import org.junit.Test; import java.util.Collection; @@ -53,7 +52,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class TriggeredWatchStoreTests extends ESTestCase { - private ClientProxy clientProxy; private TriggeredWatch.Parser parser; private TriggeredWatchStore triggeredWatchStore; @@ -66,8 +64,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { triggeredWatchStore.start(); } - @Test - public void testLoadWatchRecords_noPriorHistoryIndices() throws Exception { + public void testLoadWatchRecordsNoPriorHistoryIndices() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("name")); MetaData.Builder metaDateBuilder = MetaData.builder(); csBuilder.metaData(metaDateBuilder); @@ -80,8 +77,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { verifyZeroInteractions(clientProxy); } - @Test - public void testLoadWatchRecords_noActivePrimaryShards() throws Exception { + public void testLoadWatchRecordsNoActivePrimaryShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -125,8 +121,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { verifyZeroInteractions(clientProxy); } - @Test - public void testLoadWatchRecords_refreshNotHittingAllShards() throws Exception { + public void testLoadWatchRecordsRefreshNotHittingAllShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -160,8 +155,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { verify(clientProxy, times(1)).refresh(any(RefreshRequest.class)); } - @Test - public void testLoadWatchRecords_searchNotHittingAllShards() throws Exception { + public void testLoadWatchRecordsSearchNotHittingAllShards() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -204,8 +198,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { verify(clientProxy, times(1)).clearScroll(anyString()); } - @Test - public void testLoadWatchRecords_noHistoryEntries() throws Exception { + public void testLoadWatchRecordsNoHistoryEntries() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -247,8 +240,7 @@ public class TriggeredWatchStoreTests extends ESTestCase { verify(clientProxy, times(1)).clearScroll(anyString()); } - @Test - public void testLoadWatchRecords_foundHistoryEntries() throws Exception { + public void testLoadWatchRecordsFoundHistoryEntries() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); @@ -317,5 +309,4 @@ public class TriggeredWatchStoreTests extends ESTestCase { when(refreshResponse.getSuccessfulShards()).thenReturn(successful); return refreshResponse; } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchTests.java index 7ff54e3361d..2b3fc82489a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/execution/TriggeredWatchTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.Watch; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import static org.hamcrest.Matchers.equalTo; @@ -23,8 +22,6 @@ import static org.hamcrest.Matchers.equalTo; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class TriggeredWatchTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testParser() throws Exception { Watch watch = WatcherTestUtils.createTestWatch("fired_test", scriptService(), watcherHttpClient(), noopEmailService(), logger); ScheduleTriggerEvent event = new ScheduleTriggerEvent(watch.id(), DateTime.now(DateTimeZone.UTC), DateTime.now(DateTimeZone.UTC)); @@ -43,6 +40,4 @@ public class TriggeredWatchTests extends AbstractWatcherIntegrationTestCase { private TriggeredWatch.Parser triggeredWatchParser() { return internalCluster().getInstance(TriggeredWatch.Parser.class); } - - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreSettingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreSettingsTests.java index 819c37dd1d4..f17145b8b1f 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreSettingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreSettingsTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.watcher.WatcherModule; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; -import org.junit.Test; import static org.elasticsearch.test.ESIntegTestCase.Scope.TEST; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -24,8 +23,6 @@ import static org.hamcrest.core.Is.is; @TestLogging("cluster:DEBUG,action.admin.cluster.settings:DEBUG,watcher:DEBUG") @ESIntegTestCase.ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 1) public class HistoryStoreSettingsTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testChangeSettings() throws Exception { GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(WatcherModule.HISTORY_TEMPLATE_NAME).get(); assertThat(response.getIndexTemplates().get(0).getSettings().get("index.number_of_shards"), equalTo("1")); @@ -52,8 +49,7 @@ public class HistoryStoreSettingsTests extends AbstractWatcherIntegrationTestCas }); } - @Test - public void testChangeSettings_ignoringForbiddenSetting() throws Exception { + public void testChangeSettingsIgnoringForbiddenSetting() throws Exception { GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(WatcherModule.HISTORY_TEMPLATE_NAME).get(); assertThat(response.getIndexTemplates().get(0).getSettings().get("index.number_of_shards"), equalTo("1")); assertThat(response.getIndexTemplates().get(0).getSettings().getAsBoolean("index.mapper.dynamic", null), is(false)); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java index c760fa1f2e2..2ee85369714 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryStoreTests.java @@ -16,18 +16,19 @@ import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Test; import org.mockito.Matchers; import static org.elasticsearch.watcher.test.WatcherMatchers.indexRequest; +import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.joda.time.DateTimeZone.UTC; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** */ public class HistoryStoreTests extends ESTestCase { - private HistoryStore historyStore; private ClientProxy clientProxy; @@ -38,7 +39,6 @@ public class HistoryStoreTests extends ESTestCase { historyStore.start(); } - @Test public void testPut() throws Exception { Wid wid = new Wid("_name", 0, new DateTime(0, UTC)); ScheduleTriggerEvent event = new ScheduleTriggerEvent(wid.watchId(), new DateTime(0, UTC), new DateTime(0, UTC)); @@ -51,8 +51,7 @@ public class HistoryStoreTests extends ESTestCase { verify(clientProxy).index(Matchers.any(), Matchers.any()); } - @Test(expected = IllegalStateException.class) - public void testPut_stopped() throws Exception { + public void testPutStopped() throws Exception { Wid wid = new Wid("_name", 0, new DateTime(0, UTC)); ScheduleTriggerEvent event = new ScheduleTriggerEvent(wid.watchId(), new DateTime(0, UTC), new DateTime(0, UTC)); WatchRecord watchRecord = new WatchRecord(wid, event, ExecutionState.EXECUTED, null); @@ -60,18 +59,18 @@ public class HistoryStoreTests extends ESTestCase { historyStore.stop(); try { historyStore.put(watchRecord); + fail("Expected IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("unable to persist watch record history store is not ready")); } finally { historyStore.start(); } - fail(); } - @Test public void testIndexNameGeneration() { assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(0, UTC)), equalTo(".watch_history-1970.01.01")); assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(100000000000L, UTC)), equalTo(".watch_history-1973.03.03")); assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(1416582852000L, UTC)), equalTo(".watch_history-2014.11.21")); assertThat(HistoryStore.getHistoryIndexNameForTime(new DateTime(2833165811000L, UTC)), equalTo(".watch_history-2059.10.12")); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateEmailMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateEmailMappingsTests.java index 10269cdb774..92e4a5ec733 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateEmailMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateEmailMappingsTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.junit.After; -import org.junit.Test; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -33,13 +32,11 @@ import static org.hamcrest.Matchers.notNullValue; * not analyzed so they can be used in aggregations */ public class HistoryTemplateEmailMappingsTests extends AbstractWatcherIntegrationTestCase { - static final String USERNAME = "_user"; static final String PASSWORD = "_passwd"; private EmailServer server; - @After public void cleanup() throws Exception { server.stop(); @@ -74,7 +71,6 @@ public class HistoryTemplateEmailMappingsTests extends AbstractWatcherIntegratio .build(); } - @Test public void testEmailFields() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(interval("5s"))) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateHttpMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateHttpMappingsTests.java index 87a391d9320..7be56714619 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateHttpMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateHttpMappingsTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.watcher.history; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.QueueDispatcher; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.aggregations.Aggregations; @@ -18,7 +19,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.net.BindException; @@ -38,7 +38,6 @@ import static org.hamcrest.Matchers.notNullValue; * not analyzed so they can be used in aggregations */ public class HistoryTemplateHttpMappingsTests extends AbstractWatcherIntegrationTestCase { - private int webPort; private MockWebServer webServer; @@ -74,7 +73,6 @@ public class HistoryTemplateHttpMappingsTests extends AbstractWatcherIntegration return false; // remove shield noise from this test } - @Test public void testHttpFields() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(interval("5s"))) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateIndexActionMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateIndexActionMappingsTests.java index b67d52e3f50..11fd4c6e9bb 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateIndexActionMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateIndexActionMappingsTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -27,7 +26,6 @@ import static org.hamcrest.Matchers.notNullValue; * not analyzed so they can be used in aggregations */ public class HistoryTemplateIndexActionMappingsTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; // just to have better control over the triggers @@ -38,7 +36,6 @@ public class HistoryTemplateIndexActionMappingsTests extends AbstractWatcherInte return false; // remove shield noise from this test } - @Test public void testIndexActionFields() throws Exception { String index = "the-index"; String type = "the-type"; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateSearchInputMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateSearchInputMappingsTests.java index 0249c7bfb52..8c7413b446b 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateSearchInputMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateSearchInputMappingsTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; @@ -32,7 +31,6 @@ import static org.hamcrest.Matchers.notNullValue; * not analyzed so they can be used in aggregations */ public class HistoryTemplateSearchInputMappingsTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; // just to have better control over the triggers @@ -43,7 +41,6 @@ public class HistoryTemplateSearchInputMappingsTests extends AbstractWatcherInte return false; // remove shield noise from this test } - @Test public void testHttpFields() throws Exception { String index = "the-index"; String type = "the-type"; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTimeMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTimeMappingsTests.java index 18f0f92ecd6..01dc57b8226 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTimeMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTimeMappingsTests.java @@ -6,13 +6,13 @@ package org.elasticsearch.watcher.history; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; + import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.io.IOException; import java.util.Map; @@ -31,7 +31,6 @@ import static org.hamcrest.Matchers.notNullValue; * This test makes sure that the different time fields in the watch_record are mapped as date types */ public class HistoryTemplateTimeMappingsTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; // just to have better control over the triggers @@ -42,7 +41,6 @@ public class HistoryTemplateTimeMappingsTests extends AbstractWatcherIntegration return false; // remove shield noise from this test } - @Test public void testTimeFields() throws Exception { PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(interval("5s"))) diff --git a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTransformMappingsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTransformMappingsTests.java index 2c9829657b2..bac674d7821 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTransformMappingsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/history/HistoryTemplateTransformMappingsTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.io.IOException; import java.util.Map; @@ -36,7 +35,6 @@ import static org.hamcrest.Matchers.notNullValue; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class HistoryTemplateTransformMappingsTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; // just to have better control over the triggers @@ -47,7 +45,6 @@ public class HistoryTemplateTransformMappingsTests extends AbstractWatcherIntegr return false; // remove shield noise from this test } - @Test public void testTransformFields() throws Exception { String index = "the-index"; String type = "the-type"; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java index 5b3059ea6f3..0f2520ecf25 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/InputRegistryTests.java @@ -9,33 +9,38 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static java.util.Collections.emptyMap; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.hamcrest.Matchers.containsString; /** * */ public class InputRegistryTests extends ESTestCase { - - @Test(expected = ElasticsearchParseException.class) - public void testParse_EmptyInput() throws Exception { + public void testParseEmptyInput() throws Exception { InputRegistry registry = new InputRegistry(emptyMap()); XContentParser parser = JsonXContent.jsonXContent.createParser( jsonBuilder().startObject().endObject().bytes()); parser.nextToken(); - registry.parse("_id", parser); - fail("expecting an exception when trying to parse an empty input"); + try { + registry.parse("_id", parser); + fail("expecting an exception when trying to parse an empty input"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected field indicating the input type, but found an empty object instead")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_ArrayInput() throws Exception { + public void testParseArrayInput() throws Exception { InputRegistry registry = new InputRegistry(emptyMap()); XContentParser parser = JsonXContent.jsonXContent.createParser( jsonBuilder().startArray().endArray().bytes()); parser.nextToken(); - registry.parse("_id", parser); - fail("expecting an exception when trying to parse an input that is not an object"); + try { + registry.parse("_id", parser); + fail("expecting an exception when trying to parse an input that is not an object"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected an object representing the input, but found [START_ARRAY] instead")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputIntegrationTests.java index af999107741..a1ce86b885d 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputIntegrationTests.java @@ -5,6 +5,7 @@ */ package org.elasticsearch.watcher.input.http; +import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.settings.Settings; @@ -20,7 +21,6 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.trigger.schedule.IntervalSchedule; -import org.junit.Test; import java.net.InetSocketAddress; @@ -37,11 +37,8 @@ import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; import static org.hamcrest.Matchers.equalTo; -import org.apache.lucene.util.LuceneTestCase.AwaitsFix; - @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class HttpInputIntegrationTests extends AbstractWatcherIntegrationTestCase { - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -50,7 +47,6 @@ public class HttpInputIntegrationTests extends AbstractWatcherIntegrationTestCas .build(); } - @Test @TestLogging("watcher.support.http:TRACE") public void testHttpInput() throws Exception { createIndex("index"); @@ -75,8 +71,7 @@ public class HttpInputIntegrationTests extends AbstractWatcherIntegrationTestCas assertWatchWithMinimumPerformedActionsCount("_name", 1, false); } - @Test - public void testHttpInput_clusterStats() throws Exception { + public void testHttpInputClusterStats() throws Exception { InetSocketAddress address = internalCluster().httpAddresses()[0]; PutWatchResponse putWatchResponse = watcherClient().preparePutWatch("_name") .setSource(watchBuilder() @@ -96,7 +91,6 @@ public class HttpInputIntegrationTests extends AbstractWatcherIntegrationTestCas assertWatchWithMinimumPerformedActionsCount("_name", 1, false); } - @Test @TestLogging("watcher.support.http:TRACE") public void testInputFiltering() throws Exception { WatcherClient watcherClient = watcherClient(); @@ -153,5 +147,4 @@ public class HttpInputIntegrationTests extends AbstractWatcherIntegrationTestCas XContentSource source = xContentSource(searchResponse.getHits().getAt(0).getSourceRef()); assertThat(source.getValue("result.input.payload.hits.total"), equalTo((Object) 1)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java index 6a3c14ef4ac..df7b5c0b05a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/http/HttpInputTests.java @@ -45,7 +45,6 @@ import org.elasticsearch.watcher.watch.WatchStatus; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Test; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -67,7 +66,6 @@ import static org.mockito.Mockito.when; /** */ public class HttpInputTests extends ESTestCase { - private HttpClient httpClient; private HttpInputFactory httpParser; private SecretService secretService; @@ -82,7 +80,6 @@ public class HttpInputTests extends ESTestCase { httpParser = new HttpInputFactory(Settings.EMPTY, httpClient, templateEngine, new HttpRequest.Parser(registry), new HttpRequestTemplate.Parser(registry)); } - @Test public void testExecute() throws Exception { String host = "_host"; int port = 123; @@ -143,8 +140,7 @@ public class HttpInputTests extends ESTestCase { assertThat(result.payload().data(), equalTo(MapBuilder.newMapBuilder().put("key", "value").map())); } - @Test - public void testExecute_nonJson() throws Exception { + public void testExecuteNonJson() throws Exception { String host = "_host"; int port = 123; HttpRequestTemplate.Builder request = HttpRequestTemplate.builder(host, port) @@ -174,8 +170,6 @@ public class HttpInputTests extends ESTestCase { assertThat(result.payload().data().get("_value").toString(), equalTo(notJson)); } - - @Test public void testParser() throws Exception { final HttpMethod httpMethod = rarely() ? null : randomFrom(HttpMethod.values()); Scheme scheme = randomFrom(Scheme.HTTP, Scheme.HTTPS, null); @@ -242,7 +236,6 @@ public class HttpInputTests extends ESTestCase { } } - @Test(expected = IllegalArgumentException.class) public void testParser_invalidHttpMethod() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .startObject("request") @@ -252,7 +245,11 @@ public class HttpInputTests extends ESTestCase { .endObject(); XContentParser parser = XContentHelper.createParser(builder.bytes()); parser.nextToken(); - httpParser.parseInput("_id", parser); + try { + httpParser.parseInput("_id", parser); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("unsupported http method [_METHOD]")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java index 1efe9676976..54993ac2fea 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/search/SearchInputTests.java @@ -39,7 +39,6 @@ import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStatus; import org.joda.time.DateTime; import org.joda.time.chrono.ISOChronology; -import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -69,7 +68,6 @@ import static org.joda.time.DateTimeZone.UTC; */ @ClusterScope(scope = SUITE, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 1) public class SearchInputTests extends ESIntegTestCase { - private final static String TEMPLATE_QUERY = "{\"query\":{\"filtered\":{\"query\":{\"match\":{\"event_type\":{\"query\":\"a\"," + "\"type\":\"boolean\"}}},\"filter\":{\"range\":{\"_timestamp\":" + "{\"from\":\"{{ctx.trigger.scheduled_time}}||-{{seconds_param}}\",\"to\":\"{{ctx.trigger.scheduled_time}}\"," + @@ -106,7 +104,6 @@ public class SearchInputTests extends ESIntegTestCase { .build(); } - @Test public void testExecute() throws Exception { SearchSourceBuilder searchSourceBuilder = searchSource().query( boolQuery().must(matchQuery("event_type", "a")).must(rangeQuery("_timestamp").from("{{ctx.trigger.scheduled_time}}||-30s").to("{{ctx.trigger.triggered_time}}"))); @@ -139,8 +136,7 @@ public class SearchInputTests extends ESIntegTestCase { assertEquals(result.executedRequest().indicesOptions(), request.indicesOptions()); } - @Test - public void testSearch_InlineTemplate() throws Exception { + public void testSearchInlineTemplate() throws Exception { WatchExecutionContext ctx = createContext(); final String expectedTemplateString = "{\"query\":{\"filtered\":{\"query\":{\"match\":{\"event_type\":{\"query\":\"a\"," @@ -174,8 +170,7 @@ public class SearchInputTests extends ESIntegTestCase { assertThat(executedResult.executedRequest().template(), equalTo(expectedTemplate)); } - @Test - public void testSearch_IndexedTemplate() throws Exception { + public void testSearchIndexedTemplate() throws Exception { WatchExecutionContext ctx = createContext(); PutIndexedScriptRequest indexedScriptRequest = client().preparePutIndexedScript("mustache","test-template", TEMPLATE_QUERY).request(); @@ -197,8 +192,7 @@ public class SearchInputTests extends ESIntegTestCase { assertThat(resultTemplate.getType(), equalTo(ScriptType.INDEXED)); } - @Test - public void testSearch_OndiskTemplate() throws Exception { + public void testSearchOnDiskTemplate() throws Exception { WatchExecutionContext ctx = createContext(); Map params = new HashMap<>(); @@ -215,7 +209,6 @@ public class SearchInputTests extends ESIntegTestCase { assertThat(resultTemplate.getType(), equalTo(ScriptType.FILE)); } - @Test public void testDifferentSearchType() throws Exception { SearchSourceBuilder searchSourceBuilder = searchSource().query( boolQuery().must(matchQuery("event_type", "a")).must(rangeQuery("_timestamp").from("{{ctx.trigger.scheduled_time}}||-30s").to("{{ctx.trigger.triggered_time}}")) @@ -251,8 +244,7 @@ public class SearchInputTests extends ESIntegTestCase { assertEquals(result.executedRequest().indicesOptions(), request.indicesOptions()); } - @Test - public void testParser_Valid() throws Exception { + public void testParserValid() throws Exception { SearchRequest request = client().prepareSearch() .setSearchType(ExecutableSearchInput.DEFAULT_SEARCH_TYPE) .request() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java b/watcher/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java index 0fd20ce5c89..d79ec97d568 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/input/simple/SimpleInputTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.watcher.input.ExecutableInput; import org.elasticsearch.watcher.input.Input; import org.elasticsearch.watcher.input.InputFactory; import org.elasticsearch.watcher.watch.Payload; -import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; @@ -23,13 +22,12 @@ import java.util.List; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.hamcrest.Matchers.containsString; /** */ public class SimpleInputTests extends ESTestCase { - - @Test - public void textExecute() throws Exception { + public void testExecute() throws Exception { Map data = new HashMap<>(); data.put("foo", "bar"); data.put("baz", new ArrayList() ); @@ -41,9 +39,7 @@ public class SimpleInputTests extends ESTestCase { assertTrue(baz.isEmpty()); } - - @Test - public void testParser_Valid() throws Exception { + public void testParserValid() throws Exception { Map data = new HashMap<>(); data.put("foo", "bar"); data.put("baz", new ArrayList()); @@ -62,17 +58,17 @@ public class SimpleInputTests extends ESTestCase { assertTrue(baz.isEmpty()); } - - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid() throws Exception { - + public void testParserInvalid() throws Exception { XContentBuilder jsonBuilder = jsonBuilder().value("just a string"); InputFactory parser = new SimpleInputFactory(Settings.builder().build()); XContentParser xContentParser = JsonXContent.jsonXContent.createParser(jsonBuilder.bytes()); xContentParser.nextToken(); - parser.parseInput("_id", xContentParser); - fail("[simple] input parse should fail with an InputException for an empty json object"); + try { + parser.parseInput("_id", xContentParser); + fail("[simple] input parse should fail with an InputException for an empty json object"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected an object but found [VALUE_STRING] instead")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/license/LicenseTests.java b/watcher/src/test/java/org/elasticsearch/watcher/license/LicenseTests.java index 0b160d1b343..1c51760d619 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/license/LicenseTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/license/LicenseTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.license.plugin.core.LicenseState; import org.elasticsearch.license.plugin.core.Licensee; import org.elasticsearch.license.plugin.core.LicenseeRegistry; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.ArrayList; import java.util.List; @@ -20,10 +19,8 @@ import java.util.List; import static org.hamcrest.Matchers.is; public class LicenseTests extends ESTestCase { - private SimpleLicenseeRegistry licenseeRegistry = new SimpleLicenseeRegistry(); - @Test public void testPlatinumGoldTrialLicenseCanDoEverything() throws Exception { licenseeRegistry.setOperationMode(randomFrom(License.OperationMode.PLATINUM, License.OperationMode.GOLD, License.OperationMode.TRIAL)); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -32,7 +29,6 @@ public class LicenseTests extends ESTestCase { assertLicenseGoldPlatinumTrialBehaviour(watcherLicensee); } - @Test public void testBasicLicenseIsDisabled() throws Exception { licenseeRegistry.setOperationMode(License.OperationMode.BASIC); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -41,7 +37,6 @@ public class LicenseTests extends ESTestCase { assertLicenseBasicOrNoneOrExpiredBehaviour(watcherLicensee); } - @Test public void testNoLicenseDoesNotWork() { licenseeRegistry.setOperationMode(License.OperationMode.BASIC); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -51,7 +46,6 @@ public class LicenseTests extends ESTestCase { assertLicenseBasicOrNoneOrExpiredBehaviour(watcherLicensee); } - @Test public void testExpiredPlatinumGoldTrialLicenseIsRestricted() throws Exception { licenseeRegistry.setOperationMode(randomFrom(License.OperationMode.PLATINUM, License.OperationMode.GOLD, License.OperationMode.TRIAL)); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -61,7 +55,6 @@ public class LicenseTests extends ESTestCase { assertLicenseBasicOrNoneOrExpiredBehaviour(watcherLicensee); } - @Test public void testUpgradingFromBasicLicenseWorks() { licenseeRegistry.setOperationMode(License.OperationMode.BASIC); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -73,7 +66,6 @@ public class LicenseTests extends ESTestCase { assertLicenseGoldPlatinumTrialBehaviour(watcherLicensee); } - @Test public void testDowngradingToBasicLicenseWorks() { licenseeRegistry.setOperationMode(randomFrom(License.OperationMode.PLATINUM, License.OperationMode.GOLD, License.OperationMode.TRIAL)); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -85,7 +77,6 @@ public class LicenseTests extends ESTestCase { assertLicenseBasicOrNoneOrExpiredBehaviour(watcherLicensee); } - @Test public void testUpgradingExpiredLicenseWorks() { licenseeRegistry.setOperationMode(randomFrom(License.OperationMode.PLATINUM, License.OperationMode.GOLD, License.OperationMode.TRIAL)); WatcherLicensee watcherLicensee = new WatcherLicensee(Settings.EMPTY, licenseeRegistry); @@ -113,7 +104,6 @@ public class LicenseTests extends ESTestCase { } public static class SimpleLicenseeRegistry extends AbstractComponent implements LicenseeRegistry { - private final List licensees = new ArrayList<>(); private License.OperationMode operationMode; diff --git a/watcher/src/test/java/org/elasticsearch/watcher/shield/BasicShieldTests.java b/watcher/src/test/java/org/elasticsearch/watcher/shield/BasicShieldTests.java index a4dab054100..bc6952d12dd 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/shield/BasicShieldTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/shield/BasicShieldTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.watcher.trigger.TriggerEvent; import org.elasticsearch.watcher.trigger.schedule.IntervalSchedule; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.joda.time.DateTime; -import org.junit.Test; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; @@ -29,7 +28,6 @@ import static org.hamcrest.core.Is.is; import static org.joda.time.DateTimeZone.UTC; public class BasicShieldTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean enableShield() { return true; @@ -44,7 +42,6 @@ public class BasicShieldTests extends AbstractWatcherIntegrationTestCase { .build(); } - @Test public void testNoAuthorization() throws Exception { try { watcherClient().prepareWatcherStats().get(); @@ -55,7 +52,6 @@ public class BasicShieldTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testWatcherMonitorRole() throws Exception { // stats and get watch apis require at least monitor role: String token = basicAuthHeaderValue("test", new SecuredString("changeme".toCharArray())); @@ -100,7 +96,6 @@ public class BasicShieldTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testWatcherAdminRole() throws Exception { // put, execute and delete watch apis requires watcher admin role: String token = basicAuthHeaderValue("test", new SecuredString("changeme".toCharArray())); @@ -162,5 +157,4 @@ public class BasicShieldTests extends AbstractWatcherIntegrationTestCase { .get(); assertThat(getWatchResponse.isFound(), is(false)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/DynamicIndexNameIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/DynamicIndexNameIntegrationTests.java index 81473b9f915..de57fd2ff38 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/DynamicIndexNameIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/DynamicIndexNameIntegrationTests.java @@ -14,7 +14,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.trigger.schedule.IntervalSchedule; import org.joda.time.format.DateTimeFormat; -import org.junit.Test; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; @@ -33,7 +32,6 @@ import static org.hamcrest.Matchers.is; /** */ public class DynamicIndexNameIntegrationTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; @@ -44,7 +42,6 @@ public class DynamicIndexNameIntegrationTests extends AbstractWatcherIntegration return false; // reduce noise } - @Test public void testDynamicIndexAction() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch("_id") @@ -75,7 +72,6 @@ public class DynamicIndexNameIntegrationTests extends AbstractWatcherIntegration }); } - @Test public void testDynamicIndexSearchInput() throws Exception { final String indexName = "idx-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(timeWarp().clock().nowUTC()); createIndex(indexName); @@ -101,7 +97,6 @@ public class DynamicIndexNameIntegrationTests extends AbstractWatcherIntegration assertThat(response.getHits().getTotalHits(), is(1L)); } - @Test public void testDynamicIndexSearchTransform() throws Exception { String indexName = "idx-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(timeWarp().clock().nowUTC()); createIndex(indexName); @@ -132,5 +127,4 @@ public class DynamicIndexNameIntegrationTests extends AbstractWatcherIntegration }); assertThat(response.getHits().getTotalHits(), is(1L)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/FilterXContentTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/FilterXContentTests.java index b4bee911152..44393fb117a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/FilterXContentTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/FilterXContentTests.java @@ -12,9 +12,12 @@ import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; import org.hamcrest.Matchers; -import org.junit.Test; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.equalTo; @@ -22,8 +25,6 @@ import static org.hamcrest.Matchers.equalTo; /** */ public class FilterXContentTests extends ESTestCase { - - @Test public void testPayloadFiltering() throws Exception { Map data = new HashMap<>(); data.put("key0", "value1"); @@ -54,7 +55,6 @@ public class FilterXContentTests extends ESTestCase { } } - @Test public void testNestedPayloadFiltering() throws Exception { Map data = new HashMap<>(); data.put("leaf1", MapBuilder.newMapBuilder().put("key1", "value1").put("key2", true).map()); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java index 77506ff9a1e..089e344b5bb 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/VariablesTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.watcher.trigger.TriggerEvent; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.Payload; import org.joda.time.DateTime; -import org.junit.Test; import java.util.Map; @@ -28,8 +27,6 @@ import static org.joda.time.DateTimeZone.UTC; * */ public class VariablesTests extends ESTestCase { - - @Test public void testCreateCtxModel() throws Exception { DateTime scheduledTime = DateTime.now(UTC); DateTime triggeredTime = scheduledTime.plusMillis(50); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherDateTimeUtilsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherDateTimeUtilsTests.java index a24f1cb1342..67636cb0334 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherDateTimeUtilsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherDateTimeUtilsTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.HashMap; import java.util.Map; @@ -25,6 +24,7 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.test.WatcherTestUtils.xContentParser; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -32,9 +32,7 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class WatcherDateTimeUtilsTests extends ESTestCase { - - @Test(expected = ElasticsearchParseException.class) - public void testParseTimeValue_Numeric() throws Exception { + public void testParseTimeValueNumeric() throws Exception { TimeValue value = new TimeValue(randomInt(100), randomFrom(TimeUnit.values())); long millis = value.getMillis(); XContentBuilder xContentBuilder = jsonBuilder().startObject(); @@ -48,13 +46,16 @@ public class WatcherDateTimeUtilsTests extends ESTestCase { parser.nextToken(); // field name parser.nextToken(); // value - TimeValue parsed = WatcherDateTimeUtils.parseTimeValue(parser, "test"); - assertThat(parsed, notNullValue()); - assertThat(parsed.millis(), is(value.millis())); + try { + WatcherDateTimeUtils.parseTimeValue(parser, "test"); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), either(is("failed to parse time unit")) + .or(is("could not parse time value. expected either a string or a null value but found [VALUE_NUMBER] instead"))); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParseTimeValue_Numeric_Negative() throws Exception { + public void testParseTimeValueNumericNegative() throws Exception { TimeValue value = new TimeValue(randomIntBetween(1, 100), randomFrom(MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS)); XContentParser parser = xContentParser(jsonBuilder().startObject().field("value", -1 * value.getMillis()).endObject()); @@ -62,11 +63,15 @@ public class WatcherDateTimeUtilsTests extends ESTestCase { parser.nextToken(); // field name parser.nextToken(); // value - WatcherDateTimeUtils.parseTimeValue(parser, "test"); + try { + WatcherDateTimeUtils.parseTimeValue(parser, "test"); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse time value. expected either a string or a null value but found [VALUE_NUMBER] instead")); + } } - @Test - public void testParseTimeValue_String() throws Exception { + public void testParseTimeValueString() throws Exception { int value = randomIntBetween(2, 200); Map values = new HashMap<>(); values.put(value + "s", TimeValue.timeValueSeconds(value)); @@ -85,8 +90,7 @@ public class WatcherDateTimeUtilsTests extends ESTestCase { assertThat(parsed.millis(), is(values.get(key).millis())); } - @Test(expected = ElasticsearchParseException.class) - public void testParseTimeValue_String_Negative() throws Exception { + public void testParseTimeValueStringNegative() throws Exception { int value = -1 * randomIntBetween(2, 200); Map values = new HashMap<>(); values.put(value + "s", TimeValue.timeValueSeconds(value)); @@ -100,10 +104,15 @@ public class WatcherDateTimeUtilsTests extends ESTestCase { parser.nextToken(); // field name parser.nextToken(); // value - WatcherDateTimeUtils.parseTimeValue(parser, "test"); + try { + WatcherDateTimeUtils.parseTimeValue(parser, "test"); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("failed to parse time unit")); + } } - public void testParseTimeValue_Null() throws Exception { + public void testParseTimeValueNull() throws Exception { XContentParser parser = xContentParser(jsonBuilder().startObject().nullField("value").endObject()); parser.nextToken(); // start object parser.nextToken(); // field name diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistryTests.java index e11c695d9b5..afe23aa6100 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/WatcherIndexTemplateRegistryTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.watcher.WatcherModule; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; -import org.junit.Test; import static org.elasticsearch.test.ESIntegTestCase.Scope.TEST; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @@ -21,8 +20,6 @@ import static org.hamcrest.core.Is.is; */ @ESIntegTestCase.ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 1) public class WatcherIndexTemplateRegistryTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testTemplates() throws Exception { assertAcked( client().admin().cluster().prepareUpdateSettings() @@ -58,5 +55,4 @@ public class WatcherIndexTemplateRegistryTests extends AbstractWatcherIntegratio } }); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/clock/ClockTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/clock/ClockTests.java index c20fae37c34..de6ff6c4476 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/clock/ClockTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/clock/ClockTests.java @@ -6,20 +6,16 @@ package org.elasticsearch.watcher.support.clock; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; -import static org.joda.time.DateTimeZone.UTC; import static org.hamcrest.Matchers.equalTo; +import static org.joda.time.DateTimeZone.UTC; /** */ public class ClockTests extends ESTestCase { - - @Test - public void test_now_UTC() { + public void testNowUTC() { Clock clockMock = new ClockMock(); assertThat(clockMock.now(UTC).getZone(), equalTo(UTC)); assertThat(SystemClock.INSTANCE.now(UTC).getZone(), equalTo(UTC)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/concurrent/FairKeyedLockTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/concurrent/FairKeyedLockTests.java index 599940eae7d..33594aed20c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/concurrent/FairKeyedLockTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/concurrent/FairKeyedLockTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.watcher.support.concurrent; import org.elasticsearch.test.ESTestCase; import org.hamcrest.Matchers; -import org.junit.Test; import java.util.Map; import java.util.Set; @@ -17,15 +16,15 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; /** */ public class FairKeyedLockTests extends ESTestCase { - - @Test - public void checkIfMapEmptyAfterLotsOfAcquireAndReleases() throws InterruptedException { + public void testIfMapEmptyAfterLotsOfAcquireAndReleases() throws InterruptedException { ConcurrentHashMap counter = new ConcurrentHashMap<>(); ConcurrentHashMap safeCounter = new ConcurrentHashMap<>(); FairKeyedLock connectionLock = randomBoolean() ? new FairKeyedLock.GlobalLockable() : new FairKeyedLock(); @@ -63,13 +62,15 @@ public class FairKeyedLockTests extends ESTestCase { } } - @Test(expected = IllegalArgumentException.class) - public void checkCannotAcquireTwoLocksGlobal() throws InterruptedException { + public void testCannotAcquireTwoLocksGlobal() throws InterruptedException { FairKeyedLock.GlobalLockable connectionLock = new FairKeyedLock.GlobalLockable<>(); String name = randomRealisticUnicodeOfLength(scaledRandomIntBetween(10, 50)); connectionLock.acquire(name); try { connectionLock.acquire(name); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("Lock already acquired")); } finally { connectionLock.release(name); connectionLock.globalLock().lock(); @@ -77,15 +78,18 @@ public class FairKeyedLockTests extends ESTestCase { } } - @Test(expected = IllegalArgumentException.class) - public void checkCannotAcquireTwoLocks() throws InterruptedException { + public void testCannotAcquireTwoLocks() throws InterruptedException { FairKeyedLock connectionLock = randomBoolean() ? new FairKeyedLock.GlobalLockable() : new FairKeyedLock(); String name = randomRealisticUnicodeOfLength(scaledRandomIntBetween(10, 50)); connectionLock.acquire(name); - connectionLock.acquire(name); + try { + connectionLock.acquire(name); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("Lock already acquired")); + } } - @Test public void testTryAquire() throws InterruptedException { final FairKeyedLock connectionLock = randomBoolean() ? new FairKeyedLock.GlobalLockable() : new FairKeyedLock(); final String name = randomRealisticUnicodeOfLength(scaledRandomIntBetween(10, 50)); @@ -116,11 +120,15 @@ public class FairKeyedLockTests extends ESTestCase { } - @Test(expected = IllegalArgumentException.class) - public void checkCannotReleaseUnacquiredLock() throws InterruptedException { + public void testCannotReleaseUnacquiredLock() throws InterruptedException { FairKeyedLock connectionLock = randomBoolean() ? new FairKeyedLock.GlobalLockable() : new FairKeyedLock(); String name = randomRealisticUnicodeOfLength(scaledRandomIntBetween(10, 50)); - connectionLock.release(name); + try { + connectionLock.release(name); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("Lock not acquired")); + } } public static class AcquireAndReleaseThread extends Thread { @@ -139,6 +147,7 @@ public class FairKeyedLockTests extends ESTestCase { this.safeCounter = safeCounter; } + @Override public void run() { try { startLatch.await(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java index e873000f146..a2192cd128a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpClientTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.watcher.support.http.auth.basic.BasicAuthFactory; import org.elasticsearch.watcher.support.secret.SecretService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.net.BindException; @@ -45,7 +44,6 @@ import static org.hamcrest.core.Is.is; /** */ public class HttpClientTests extends ESTestCase { - private MockWebServer webServer; private HttpClient httpClient; private HttpAuthRegistry authRegistry; @@ -76,7 +74,6 @@ public class HttpClientTests extends ESTestCase { webServer.shutdown(); } - @Test public void testBasics() throws Exception { int responseCode = randomIntBetween(200, 203); String body = randomAsciiOfLengthBetween(2, 8096); @@ -113,7 +110,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getHeader(headerKey), equalTo(headerValue)); } - @Test public void testNoQueryString() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequest.Builder requestBuilder = HttpRequest.builder("localhost", webPort) @@ -129,7 +125,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getBody().readUtf8Line(), nullValue()); } - @Test public void testUrlEncoding() throws Exception{ webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequest.Builder requestBuilder = HttpRequest.builder("localhost", webPort) @@ -146,7 +141,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getBody().readUtf8Line(), nullValue()); } - @Test public void testBasicAuth() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body")); HttpRequest.Builder request = HttpRequest.builder("localhost", webPort) @@ -162,7 +156,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getHeader("Authorization"), equalTo("Basic dXNlcjpwYXNz")); } - @Test public void testHttps() throws Exception { Path resource = getDataPath("/org/elasticsearch/shield/keystore/truststore-testnode-only.jks"); @@ -201,7 +194,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getBody().readUtf8Line(), equalTo("body")); } - @Test public void testHttpsClientAuth() throws Exception { Path resource = getDataPath("/org/elasticsearch/shield/keystore/testnode.jks"); Settings settings; @@ -233,7 +225,6 @@ public class HttpClientTests extends ESTestCase { assertThat(recordedRequest.getBody().readUtf8Line(), equalTo("body")); } - @Test public void testHttpClientReadKeyWithDifferentPassword() throws Exception { // This truststore doesn't have a cert with a valid SAN so hostname verification will fail if used Path resource = getDataPath("/org/elasticsearch/shield/keystore/testnode-different-passwords.jks"); @@ -274,7 +265,6 @@ public class HttpClientTests extends ESTestCase { } } - @Test public void test400Code() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(400)); HttpRequest.Builder request = HttpRequest.builder("localhost", webPort) @@ -288,7 +278,6 @@ public class HttpClientTests extends ESTestCase { assertThat(response.body(), nullValue()); } - @Test @Network public void testHttpsWithoutTruststore() throws Exception { HttpClient httpClient = new HttpClient(Settings.EMPTY, authRegistry, environment).start(); @@ -302,7 +291,6 @@ public class HttpClientTests extends ESTestCase { assertThat(response.body(), notNullValue()); } - @Test @Network public void testHttpsWithoutTruststoreAndSSLIntegrationActive() throws Exception { // Add some settings with SSL prefix to force socket factory creation @@ -323,7 +311,6 @@ public class HttpClientTests extends ESTestCase { } static class ClientAuthRequiringSSLSocketFactory extends SSLSocketFactory { - final SSLSocketFactory delegate; ClientAuthRequiringSSLSocketFactory(SSLSocketFactory delegate) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpConnectionTimeoutTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpConnectionTimeoutTests.java index c8011833356..8e812097635 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpConnectionTimeoutTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpConnectionTimeoutTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; -import org.junit.Test; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; @@ -20,11 +19,9 @@ import static org.mockito.Mockito.mock; /** */ public class HttpConnectionTimeoutTests extends ESTestCase { - // setting an unroutable IP to simulate a connection timeout private static final String UNROUTABLE_IP = "192.168.255.255"; - @Test public void testDefaultTimeout() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.EMPTY, mock(HttpAuthRegistry.class), environment).start(); @@ -48,8 +45,7 @@ public class HttpConnectionTimeoutTests extends ESTestCase { } } - @Test - public void testDefaultTimeout_Custom() throws Exception { + public void testDefaultTimeoutCustom() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() .put("watcher.http.default_connection_timeout", "5s") @@ -75,8 +71,7 @@ public class HttpConnectionTimeoutTests extends ESTestCase { } } - @Test - public void testTimeout_CustomPerRequest() throws Exception { + public void testTimeoutCustomPerRequest() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() .put("watcher.http.default_connection_timeout", "10s") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpReadTimeoutTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpReadTimeoutTests.java index 800f964bd61..2553d00333e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpReadTimeoutTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpReadTimeoutTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.watcher.support.http; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.common.settings.Settings; @@ -17,7 +18,6 @@ import org.elasticsearch.watcher.support.http.auth.HttpAuthRegistry; import org.elasticsearch.watcher.support.secret.SecretService; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.net.BindException; @@ -28,7 +28,6 @@ import static org.mockito.Mockito.mock; /** */ public class HttpReadTimeoutTests extends ESTestCase { - private MockWebServer webServer; private SecretService secretService; private int webPort; @@ -53,7 +52,6 @@ public class HttpReadTimeoutTests extends ESTestCase { webServer.shutdown(); } - @Test public void testDefaultTimeout() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.EMPTY, mock(HttpAuthRegistry.class), environment).start(); @@ -84,8 +82,7 @@ public class HttpReadTimeoutTests extends ESTestCase { } } - @Test - public void testDefaultTimeout_Custom() throws Exception { + public void testDefaultTimeoutCustom() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() @@ -119,8 +116,7 @@ public class HttpReadTimeoutTests extends ESTestCase { } } - @Test - public void testTimeout_CustomPerRequest() throws Exception { + public void testTimeoutCustomPerRequest() throws Exception { Environment environment = new Environment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java index 5e3655c9036..21146539521 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpRequestTemplateTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.watcher.support.secret.SecretService; import org.elasticsearch.watcher.support.text.TextTemplate; import org.elasticsearch.watcher.support.text.TextTemplateEngine; import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.junit.Test; import java.util.Map; @@ -34,9 +33,7 @@ import static org.hamcrest.Matchers.is; * */ public class HttpRequestTemplateTests extends ESTestCase { - - @Test - public void testBody_WithXContent() throws Exception { + public void testBodyWithXContent() throws Exception { XContentType type = randomFrom(XContentType.JSON, XContentType.YAML); HttpRequestTemplate template = HttpRequestTemplate.builder("_host", 1234) .body(XContentBuilder.builder(type.xContent()).startObject().endObject()) @@ -45,7 +42,6 @@ public class HttpRequestTemplateTests extends ESTestCase { assertThat(request.headers, hasEntry(HttpHeaders.Names.CONTENT_TYPE, type.restContentType())); } - @Test public void testBody() throws Exception { HttpRequestTemplate template = HttpRequestTemplate.builder("_host", 1234) .body("_body") @@ -54,8 +50,7 @@ public class HttpRequestTemplateTests extends ESTestCase { assertThat(request.headers.size(), is(0)); } - @Test - public void testParse_SelfGenerated() throws Exception { + public void testParseSelfGenerated() throws Exception { HttpRequestTemplate.Builder builder = HttpRequestTemplate.builder("_host", 1234); if (randomBoolean()) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java index e6d5dad50e0..918d28bda49 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/http/HttpResponseTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -28,9 +27,7 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class HttpResponseTests extends ESTestCase { - - @Test - public void testParse_SelfGenerated() throws Exception { + public void testParseSelfGenerated() throws Exception { int status = randomIntBetween(200, 600); Map headers = emptyMap(); if (randomBoolean()) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java index 871209ea5f4..3e404ee4439 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/text/TextTemplateTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.init.proxy.ScriptServiceProxy; import org.elasticsearch.watcher.support.text.xmustache.XMustacheTextTemplateEngine; import org.junit.Before; -import org.junit.Test; import java.util.HashMap; import java.util.Map; @@ -37,7 +36,6 @@ import static org.mockito.Mockito.when; * */ public class TextTemplateTests extends ESTestCase { - private ScriptServiceProxy proxy; private TextTemplateEngine engine; private ExecutableScript script; @@ -50,7 +48,6 @@ public class TextTemplateTests extends ESTestCase { engine = new XMustacheTextTemplateEngine(Settings.EMPTY, proxy); } - @Test public void testRender() throws Exception { String templateText = "_template"; Map params = singletonMap("param_key", "param_val"); @@ -67,8 +64,7 @@ public class TextTemplateTests extends ESTestCase { assertThat(engine.render(template, model), is("rendered_text")); } - @Test - public void testRender_OverridingModel() throws Exception { + public void testRenderOverridingModel() throws Exception { String templateText = "_template"; Map params = singletonMap("key", "param_val"); Map model = singletonMap("key", "model_val"); @@ -81,8 +77,7 @@ public class TextTemplateTests extends ESTestCase { assertThat(engine.render(template, model), is("rendered_text")); } - @Test - public void testRender_Defaults() throws Exception { + public void testRenderDefaults() throws Exception { String templateText = "_template"; Map model = singletonMap("key", "model_val"); @@ -93,7 +88,6 @@ public class TextTemplateTests extends ESTestCase { assertThat(engine.render(template, model), is("rendered_text")); } - @Test public void testParser() throws Exception { ScriptType type = randomScriptType(); TextTemplate template = templateBuilder(type, "_template").params(singletonMap("param_key", "param_val")).build(); @@ -118,8 +112,7 @@ public class TextTemplateTests extends ESTestCase { assertThat(parsed, equalTo(template)); } - @Test - public void testParser_ParserSelfGenerated() throws Exception { + public void testParserParserSelfGenerated() throws Exception { TextTemplate template = templateBuilder(randomScriptType(), "_template").params(singletonMap("param_key", "param_val")).build(); XContentBuilder builder = jsonBuilder().value(template); @@ -131,20 +124,22 @@ public class TextTemplateTests extends ESTestCase { assertThat(parsed, equalTo(template)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid_UnexpectedField() throws Exception { + public void testParserInvalidUnexpectedField() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .field("unknown_field", "value") .endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - TextTemplate.parse(parser); - fail("expected parse exception when encountering an unknown field"); + try { + TextTemplate.parse(parser); + fail("expected parse exception when encountering an unknown field"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("unexpected field [unknown_field]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid_UnknownScriptType() throws Exception { + public void testParserInvalidUnknownScriptType() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .field("template", "_template") .field("type", "unknown_type") @@ -153,12 +148,15 @@ public class TextTemplateTests extends ESTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - TextTemplate.parse(parser); - fail("expected parse exception when script type is unknown"); + try { + TextTemplate.parse(parser); + fail("expected parse exception when script type is unknown"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("unexpected field [template]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_Invalid_MissingText() throws Exception { + public void testParserInvalidMissingText() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .field("type", ScriptType.INDEXED) .startObject("params").endObject() @@ -166,8 +164,12 @@ public class TextTemplateTests extends ESTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - TextTemplate.parse(parser); - fail("expected parse exception when template text is missing"); + try { + TextTemplate.parse(parser); + fail("expected parse exception when template text is missing"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("unexpected field [type]")); + } } private TextTemplate.Builder templateBuilder(ScriptType type, String text) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheScriptEngineTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheScriptEngineTests.java index c97d4088455..6096a7cb57c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheScriptEngineTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheScriptEngineTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ScriptService; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.io.StringWriter; import java.io.Writer; @@ -24,7 +23,6 @@ import java.util.Map; * */ public class XMustacheScriptEngineTests extends ESTestCase { - private XMustacheScriptEngineService engine; @Before @@ -32,7 +30,6 @@ public class XMustacheScriptEngineTests extends ESTestCase { engine = new XMustacheScriptEngineService(Settings.Builder.EMPTY_SETTINGS); } - @Test public void testSimpleParameterReplace() { { String template = "__json__::GET _search {\"query\": " + "{\"boosting\": {" + "\"positive\": {\"match\": {\"body\": \"gift\"}}," @@ -59,7 +56,6 @@ public class XMustacheScriptEngineTests extends ESTestCase { } } - @Test public void testInvalidPrefixes() throws Exception { String[] specialStrings = new String[]{"\f", "\n", "\r", "\"", "\\", "\t", "\b", "__::", "__" }; String prefix = randomFrom("", "__", "____::", "___::", "____", "::", "++json__::", "__json__", "+_json__::", "__json__:"); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java index 4b9865cc9ec..b23064e4608 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/text/xmustache/XMustacheTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.script.ScriptEngineService; import org.elasticsearch.script.ScriptService; import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.junit.Test; import java.io.IOException; import java.io.StringWriter; @@ -38,7 +37,6 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class XMustacheTests extends ESTestCase { - private ScriptEngineService engine; @Before @@ -46,7 +44,6 @@ public class XMustacheTests extends ESTestCase { engine = new XMustacheScriptEngineService(Settings.EMPTY); } - @Test public void testArrayAccess() throws Exception { String template = "{{data.0}} {{data.1}}"; CompiledScript mustache = new CompiledScript(ScriptService.ScriptType.INLINE, "inline", "mustache", engine.compile(template)); @@ -73,7 +70,6 @@ public class XMustacheTests extends ESTestCase { assertThat(bytes.toUtf8(), both(containsString("foo")).and(containsString("bar"))); } - @Test public void testArrayInArrayAccess() throws Exception { String template = "{{data.0.0}} {{data.0.1}}"; CompiledScript mustache = new CompiledScript(ScriptService.ScriptType.INLINE, "inline", "mustache", engine.compile(template)); @@ -91,7 +87,6 @@ public class XMustacheTests extends ESTestCase { assertThat(bytes.toUtf8(), equalTo("foo bar")); } - @Test public void testMapInArrayAccess() throws Exception { String template = "{{data.0.key}} {{data.1.key}}"; CompiledScript mustache = new CompiledScript(ScriptService.ScriptType.INLINE, "inline", "mustache", engine.compile(template)); @@ -119,7 +114,6 @@ public class XMustacheTests extends ESTestCase { } - @Test public void testEscaping() throws Exception { XContentType contentType = randomFrom(XContentType.values()); if (rarely()) { @@ -189,5 +183,4 @@ public class XMustacheTests extends ESTestCase { private String getChars() throws IOException { return randomRealisticUnicodeOfCodepointLengthBetween(0, 10); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java index 8e3c2b8d71f..f3c7c20d03c 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/MapPathTests.java @@ -6,7 +6,6 @@ package org.elasticsearch.watcher.support.xcontent; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -22,8 +21,6 @@ import static org.hamcrest.Matchers.is; * */ public class MapPathTests extends ESTestCase { - - @Test public void testEval() throws Exception { Map map = singletonMap("key", "value"); @@ -31,8 +28,7 @@ public class MapPathTests extends ESTestCase { assertThat(ObjectPath.eval("key1", map), nullValue()); } - @Test - public void testEval_List() throws Exception { + public void testEvalList() throws Exception { List list = Arrays.asList(1, 2, 3, 4); Map map = singletonMap("key", list); @@ -40,8 +36,7 @@ public class MapPathTests extends ESTestCase { assertThat(ObjectPath.eval("key." + index, map), is(list.get(index))); } - @Test - public void testEval_Array() throws Exception { + public void testEvalArray() throws Exception { int[] array = new int[] { 1, 2, 3, 4 }; Map map = singletonMap("key", array); @@ -49,16 +44,13 @@ public class MapPathTests extends ESTestCase { assertThat(((Number) ObjectPath.eval("key." + index, map)).intValue(), is(array[index])); } - @Test - public void testEval_Map() throws Exception { + public void testEvalMap() throws Exception { Map map = singletonMap("a", singletonMap("b", "val")); assertThat(ObjectPath.eval("a.b", map), is((Object) "val")); } - - @Test - public void testEval_Mixed() throws Exception { + public void testEvalMixed() throws Exception { Map map = new HashMap<>(); Map mapA = new HashMap<>(); @@ -78,6 +70,5 @@ public class MapPathTests extends ESTestCase { assertThat(ObjectPath.eval("a.b.0.0.c.d", map), nullValue()); assertThat(ObjectPath.eval("a.b.0.0.d", map), nullValue()); assertThat(ObjectPath.eval("a.b.c", map), nullValue()); - } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/XContentSourceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/XContentSourceTests.java index 2fca51bf253..01f4306f413 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/XContentSourceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/support/xcontent/XContentSourceTests.java @@ -11,17 +11,16 @@ import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; -import static org.elasticsearch.common.xcontent.XContentFactory.*; +import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; +import static org.elasticsearch.common.xcontent.XContentFactory.smileBuilder; +import static org.elasticsearch.common.xcontent.XContentFactory.yamlBuilder; import static org.hamcrest.Matchers.is; /** * */ public class XContentSourceTests extends ESTestCase { - - @Test public void testToXContent() throws Exception { XContentBuilder builder = randomBoolean() ? jsonBuilder() : randomBoolean() ? yamlBuilder() : smileBuilder(); BytesReference bytes = randomBoolean() ? diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java index 8a0b8da06bc..25938053c43 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BasicWatcherTests.java @@ -33,7 +33,6 @@ import org.elasticsearch.watcher.trigger.schedule.Schedules; import org.elasticsearch.watcher.trigger.schedule.support.MonthTimes; import org.elasticsearch.watcher.trigger.schedule.support.WeekTimes; import org.elasticsearch.watcher.watch.WatchStore; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; @@ -68,8 +67,6 @@ import static org.hamcrest.Matchers.notNullValue; @TestLogging("watcher.trigger.schedule:TRACE") @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testIndexWatch() throws Exception { WatcherClient watcherClient = watcherClient(); createIndex("idx"); @@ -100,8 +97,7 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertThat(getWatchResponse.getSource(), notNullValue()); } - @Test - public void testIndexWatch_registerWatchBeforeTargetIndex() throws Exception { + public void testIndexWatchRegisterWatchBeforeTargetIndex() throws Exception { WatcherClient watcherClient = watcherClient(); SearchRequest searchRequest = newInputSearchRequest("idx").source(searchSource().query(termQuery("field", "value"))); watcherClient.preparePutWatch("_name") @@ -132,7 +128,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertWatchWithMinimumPerformedActionsCount("_name", 1); } - @Test public void testDeleteWatch() throws Exception { WatcherClient watcherClient = watcherClient(); SearchRequest searchRequest = newInputSearchRequest("idx").source(searchSource().query(matchAllQuery())); @@ -165,7 +160,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertThat(deleteWatchResponse.isFound(), is(false)); } - @Test public void testMalformedWatch() throws Exception { WatcherClient watcherClient = watcherClient(); createIndex("idx"); @@ -200,7 +194,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { } } - @Test public void testModifyWatches() throws Exception { SearchRequest searchRequest = newInputSearchRequest("idx") .source(searchSource().query(matchAllQuery())); @@ -259,7 +252,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertThat(count, equalTo(findNumberOfPerformedActions("_name"))); } - @Test public void testModifyWatchWithSameUnit() throws Exception { if (timeWarped()) { logger.info("Skipping testModifyWatches_ because timewarp is enabled"); @@ -294,7 +286,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertThat("Watch has been updated to 100s interval, so no new records should have been added.", historyRecordsCount("_name"), equalTo(before)); } - @Test public void testConditionSearchWithSource() throws Exception { String variable = randomFrom("ctx.execution_time", "ctx.trigger.scheduled_time", "ctx.trigger.triggered_time"); SearchSourceBuilder searchSourceBuilder = searchSource().query(boolQuery() @@ -306,7 +297,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { testConditionSearch(newInputSearchRequest("events").source(searchSourceBuilder)); } - @Test public void testConditionSearchWithIndexedTemplate() throws Exception { String variable = randomFrom("ctx.execution_time", "ctx.trigger.scheduled_time", "ctx.trigger.triggered_time"); SearchSourceBuilder searchSourceBuilder = searchSource().query(boolQuery() @@ -329,7 +319,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { testConditionSearch(searchRequest); } - @Test public void testInputFiltering() throws Exception { WatcherClient watcherClient = watcherClient(); createIndex("idx"); @@ -375,7 +364,6 @@ public class BasicWatcherTests extends AbstractWatcherIntegrationTestCase { assertThat(source.getValue("result.input.payload.hits.total"), equalTo((Object) 1)); } - @Test public void testPutWatchWithNegativeSchedule() throws Exception { try { watcherClient().preparePutWatch("_name") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java index 3c7b5f286df..e6b217b6804 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/BootStrapTests.java @@ -9,7 +9,6 @@ import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.WriteConsistencyLevel; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; -import org.joda.time.DateTime; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.junit.annotations.TestLogging; @@ -20,19 +19,18 @@ import org.elasticsearch.watcher.execution.ExecutionState; import org.elasticsearch.watcher.execution.TriggeredWatch; import org.elasticsearch.watcher.execution.TriggeredWatchStore; import org.elasticsearch.watcher.execution.Wid; -import org.elasticsearch.watcher.history.*; +import org.elasticsearch.watcher.history.HistoryStore; +import org.elasticsearch.watcher.history.WatchRecord; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStore; import org.hamcrest.Matchers; -import org.junit.Test; +import org.joda.time.DateTime; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.is; -import static org.joda.time.DateTimeZone.UTC; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -45,21 +43,21 @@ import static org.elasticsearch.watcher.input.InputBuilders.searchInput; import static org.elasticsearch.watcher.test.WatcherTestUtils.newInputSearchRequest; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; +import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsEqual.equalTo; +import static org.joda.time.DateTimeZone.UTC; /** */ @TestLogging("watcher:TRACE") @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class BootStrapTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { // timewarping isn't necessary here, because we aren't testing triggering or throttling return false; } - @Test public void testLoadMalformedWatch() throws Exception { // valid watch client().prepareIndex(WatchStore.INDEX, WatchStore.DOC_TYPE, "_id0") @@ -110,7 +108,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { assertThat(watcherClient().prepareGetWatch("_id0").get().getId(), Matchers.equalTo("_id0")); } - @Test public void testLoadMalformedWatchRecord() throws Exception { client().prepareIndex(WatchStore.INDEX, WatchStore.DOC_TYPE, "_id") .setSource(jsonBuilder().startObject() @@ -190,7 +187,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { assertThat(response.getWatchesCount(), equalTo(1l)); } - @Test public void testDeletedWhileQueued() throws Exception { DateTime now = DateTime.now(UTC); Wid wid = new Wid("_id", 1, now); @@ -217,8 +213,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { assertThat(searchResponse.getHits().getAt(0).sourceAsMap().get(WatchRecord.Field.STATE.getPreferredName()).toString(), Matchers.equalTo(ExecutionState.NOT_EXECUTED_WATCH_MISSING.toString())); } - - @Test public void testLoadExistingWatchesUponStartup() throws Exception { int numWatches = scaledRandomIntBetween(16, 128); SearchRequest searchRequest = newInputSearchRequest("my-index").source(searchSource().query(termQuery("field", "value"))); @@ -243,7 +237,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { assertThat(response.getWatchesCount(), equalTo((long) numWatches)); } - @Test @TestLogging("watcher.actions:DEBUG") public void testTriggeredWatchLoading() throws Exception { createIndex("output"); @@ -300,7 +293,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { }, 30, TimeUnit.SECONDS); } - @Test public void testMixedTriggeredWatchLoading() throws Exception { createIndex("output"); WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); @@ -352,7 +344,6 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { }); } - @Test public void testManuallyStopped() throws Exception { WatcherStatsResponse response = watcherClient().prepareWatcherStats().get(); assertThat(response.getWatcherMetaData().manuallyStopped(), is(false)); @@ -363,6 +354,4 @@ public class BootStrapTests extends AbstractWatcherIntegrationTestCase { response = watcherClient().prepareWatcherStats().get(); assertThat(response.getWatcherMetaData().manuallyStopped(), is(false)); } - - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/ExecutionVarsIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/ExecutionVarsIntegrationTests.java index 4fb84c2c34c..404c1acc4bf 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/ExecutionVarsIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/ExecutionVarsIntegrationTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.watcher.support.xcontent.XContentSource; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.util.List; import java.util.Map; @@ -35,13 +34,11 @@ import static org.hamcrest.Matchers.notNullValue; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; } - @Test public void testVars() throws Exception { WatcherClient watcherClient = watcherClient(); @@ -107,8 +104,7 @@ public class ExecutionVarsIntegrationTests extends AbstractWatcherIntegrationTes } } - @Test - public void testVars_Manual() throws Exception { + public void testVarsManual() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch("_id").setSource(watchBuilder() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/HttpSecretsIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/HttpSecretsIntegrationTests.java index b3fbfb564e9..17f594270ea 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/HttpSecretsIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/HttpSecretsIntegrationTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.watcher.test.integration; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; + import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.common.settings.Settings; @@ -29,7 +30,6 @@ import org.elasticsearch.watcher.watch.WatchStore; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.net.BindException; import java.util.Map; @@ -43,14 +43,18 @@ import static org.elasticsearch.watcher.input.InputBuilders.httpInput; import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.joda.time.DateTimeZone.UTC; /** * */ public class HttpSecretsIntegrationTests extends AbstractWatcherIntegrationTestCase { - static final String USERNAME = "_user"; static final String PASSWORD = "_passwd"; @@ -89,7 +93,6 @@ public class HttpSecretsIntegrationTests extends AbstractWatcherIntegrationTestC .build(); } - @Test public void testHttpInput() throws Exception { WatcherClient watcherClient = watcherClient(); watcherClient.preparePutWatch("_id") @@ -160,7 +163,6 @@ public class HttpSecretsIntegrationTests extends AbstractWatcherIntegrationTestC assertThat(request.getHeader("Authorization"), equalTo(ApplicableBasicAuth.headerValue(USERNAME, PASSWORD.toCharArray()))); } - @Test public void testWebhookAction() throws Exception { WatcherClient watcherClient = watcherClient(); watcherClient.preparePutWatch("_id") diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java index 7907e421004..a83dcf884cc 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/NoMasterNodeTests.java @@ -18,8 +18,8 @@ import org.elasticsearch.discovery.zen.elect.ElectMasterService; import org.elasticsearch.discovery.zen.ping.ZenPing; import org.elasticsearch.discovery.zen.ping.ZenPingService; import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing; -import org.elasticsearch.test.ESIntegTestCase.SuppressLocalMode; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; +import org.elasticsearch.test.ESIntegTestCase.SuppressLocalMode; import org.elasticsearch.test.discovery.ClusterDiscoveryConfiguration; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.watcher.WatcherService; @@ -32,7 +32,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; -import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -56,7 +55,6 @@ import static org.hamcrest.core.Is.is; @SuppressLocalMode @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class NoMasterNodeTests extends AbstractWatcherIntegrationTestCase { - private ClusterDiscoveryConfiguration.UnicastZen config; @Override @@ -81,7 +79,6 @@ public class NoMasterNodeTests extends AbstractWatcherIntegrationTestCase { .build(); } - @Test public void testSimpleFailure() throws Exception { // we need 3 hosts here because we stop the master and start another - it doesn't restart the pre-existing node... config = new ClusterDiscoveryConfiguration.UnicastZen(3, Settings.EMPTY); @@ -134,7 +131,6 @@ public class NoMasterNodeTests extends AbstractWatcherIntegrationTestCase { assertWatchWithMinimumPerformedActionsCount("my-second-watch", 1); } - @Test public void testDedicatedMasterNodeLayout() throws Exception { // Only the master nodes are in the unicast nodes list: config = new ClusterDiscoveryConfiguration.UnicastZen(11, 3, Settings.EMPTY); @@ -187,7 +183,6 @@ public class NoMasterNodeTests extends AbstractWatcherIntegrationTestCase { assertWatchWithMinimumPerformedActionsCount("_watch_id", 3, false); } - @Test public void testMultipleFailures() throws Exception { int numberOfFailures = scaledRandomIntBetween(2, 9); int numberOfWatches = scaledRandomIntBetween(numberOfFailures, 12); @@ -244,6 +239,7 @@ public class NoMasterNodeTests extends AbstractWatcherIntegrationTestCase { internalCluster().stopCurrentMasterNode(); // Can't use ensureWatcherStopped, b/c that relies on the watcher stats api which requires an elected master node assertBusy(new Runnable() { + @Override public void run () { for (Client client : clients()) { ClusterState state = client.admin().cluster().prepareState().setLocal(true).get().getState(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java index 897f20e2a60..8e129e07fd2 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatchMetadataTests.java @@ -8,8 +8,6 @@ package org.elasticsearch.watcher.test.integration; import org.apache.lucene.util.LuceneTestCase.AwaitsFix; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.test.junit.annotations.TestLogging; -import org.joda.time.DateTime; import org.elasticsearch.watcher.actions.logging.LoggingAction; import org.elasticsearch.watcher.actions.logging.LoggingLevel; import org.elasticsearch.watcher.condition.always.AlwaysCondition; @@ -22,14 +20,13 @@ import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.watcher.trigger.TriggerEvent; import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; -import org.junit.Test; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.joda.time.DateTimeZone.UTC; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; @@ -41,14 +38,13 @@ import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; +import static org.joda.time.DateTimeZone.UTC; /** * */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class WatchMetadataTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testWatchMetadata() throws Exception { Map metadata = new HashMap<>(); metadata.put("foo", "bar"); @@ -81,7 +77,6 @@ public class WatchMetadataTests extends AbstractWatcherIntegrationTestCase { assertThat(searchResponse.getHits().getTotalHits(), greaterThan(0L)); } - @Test public void testWatchMetadataAvailableAtExecution() throws Exception { Map metadata = new HashMap<>(); metadata.put("foo", "bar"); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatcherSettingsFilterTests.java b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatcherSettingsFilterTests.java index 7ad3c2e128e..fcb188a2f5e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/test/integration/WatcherSettingsFilterTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.junit.After; -import org.junit.Test; import java.io.IOException; import java.util.Map; @@ -33,7 +32,6 @@ import static org.hamcrest.Matchers.is; * */ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCase { - private CloseableHttpClient httpClient = HttpClients.createDefault(); @After @@ -53,8 +51,7 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa .build(); } - @Test - public void testGetSettings_SmtpPassword() throws Exception { + public void testGetSettingsSmtpPassword() throws Exception { String body = executeRequest("GET", "/_nodes/settings", null, null).getBody(); Map response = JsonXContent.jsonXContent.createParser(body).map(); Map nodes = (Map) response.get("nodes"); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/TransformIntegrationTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/TransformIntegrationTests.java index c9e1c6366e4..f6be9b031da 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/TransformIntegrationTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/TransformIntegrationTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.watcher.support.Script; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -32,16 +31,20 @@ import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondition; import static org.elasticsearch.watcher.input.InputBuilders.searchInput; import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; -import static org.elasticsearch.watcher.transform.TransformBuilders.*; +import static org.elasticsearch.watcher.transform.TransformBuilders.chainTransform; +import static org.elasticsearch.watcher.transform.TransformBuilders.scriptTransform; +import static org.elasticsearch.watcher.transform.TransformBuilders.searchTransform; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; /** */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCase { - @Override public Settings nodeSettings(int nodeOrdinal) { Path configDir = createTempDir(); @@ -59,7 +62,6 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas return settingsBuilder().put(super.nodeSettings(nodeOrdinal)).put("path.conf", configDir.toString()).build(); } - @Test public void testScriptTransform() throws Exception { final Script script; if (randomBoolean()) { @@ -117,7 +119,6 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas assertThat(response.getHits().getAt(0).sourceAsMap().get("key3").toString(), equalTo("20")); } - @Test public void testSearchTransform() throws Exception { createIndex("my-condition-index", "my-payload-index"); ensureGreen("my-condition-index", "my-payload-index"); @@ -165,7 +166,6 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas assertThat(response.getHits().getAt(0).sourceAsString(), containsString("mytestresult")); } - @Test public void testChainTransform() throws Exception { final Script script1 = Script.inline("return [key3 : ctx.payload.key1 + ctx.payload.key2]").lang("groovy").build(); final Script script2 = Script.inline("return [key4 : ctx.payload.key3 + 10]").lang("groovy").build(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java index f12ef5c3e1e..32dd178dbf8 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/chain/ChainTransformTests.java @@ -17,7 +17,6 @@ import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.watcher.transform.TransformFactory; import org.elasticsearch.watcher.transform.TransformRegistry; import org.elasticsearch.watcher.watch.Payload; -import org.junit.Test; import java.io.IOException; import java.util.ArrayList; @@ -40,8 +39,6 @@ import static org.mockito.Mockito.mock; * */ public class ChainTransformTests extends ESTestCase { - - @Test public void testExecute() throws Exception { ChainTransform transform = new ChainTransform( new NamedExecutableTransform.Transform("name1"), @@ -81,8 +78,7 @@ public class ChainTransformTests extends ESTestCase { assertThat(names, contains("name1", "name2", "name3")); } - @Test - public void testExecute_Failure() throws Exception { + public void testExecuteFailure() throws Exception { ChainTransform transform = new ChainTransform( new NamedExecutableTransform.Transform("name1"), new NamedExecutableTransform.Transform("name2"), @@ -114,7 +110,6 @@ public class ChainTransformTests extends ESTestCase { } - @Test public void testParser() throws Exception { TransformRegistry registry = new TransformRegistry(singletonMap("named", new NamedExecutableTransform.Factory(logger))); @@ -140,7 +135,6 @@ public class ChainTransformTests extends ESTestCase { } private static class NamedExecutableTransform extends ExecutableTransform { - private static final String TYPE = "named"; public NamedExecutableTransform(String name) { @@ -197,7 +191,6 @@ public class ChainTransformTests extends ESTestCase { } public static class Factory extends TransformFactory { - public Factory(ESLogger transformLogger) { super(transformLogger); } @@ -231,7 +224,6 @@ public class ChainTransformTests extends ESTestCase { } private static class FailingExecutableTransform extends ExecutableTransform { - private static final String TYPE = "throwing"; public FailingExecutableTransform(ESLogger logger) { @@ -244,7 +236,6 @@ public class ChainTransformTests extends ESTestCase { } public static class Transform implements org.elasticsearch.watcher.transform.Transform { - @Override public String type() { return TYPE; @@ -257,7 +248,6 @@ public class ChainTransformTests extends ESTestCase { } public static class Result extends Transform.Result { - public Result(String type) { super(type, new Exception("_error")); } @@ -269,7 +259,6 @@ public class ChainTransformTests extends ESTestCase { } public static class Factory extends TransformFactory { - public Factory(ESLogger transformLogger) { super(transformLogger); } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java index b2a2299f57e..7a024d35a67 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/script/ScriptTransformTests.java @@ -24,7 +24,6 @@ import org.elasticsearch.watcher.transform.Transform; import org.elasticsearch.watcher.watch.Payload; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.Arrays; import java.util.Collections; @@ -50,7 +49,6 @@ import static org.mockito.Mockito.when; * */ public class ScriptTransformTests extends ESTestCase { - ThreadPool tp = null; @Before @@ -63,8 +61,6 @@ public class ScriptTransformTests extends ESTestCase { tp.shutdownNow(); } - - @Test public void testExecute_MapValue() throws Exception { ScriptServiceProxy service = mock(ScriptServiceProxy.class); ScriptType type = randomFrom(ScriptType.values()); @@ -93,8 +89,7 @@ public class ScriptTransformTests extends ESTestCase { assertThat(result.payload().data(), equalTo(transformed)); } - @Test - public void testExecute_MapValue_Failure() throws Exception { + public void testExecuteMapValueFailure() throws Exception { ScriptServiceProxy service = mock(ScriptServiceProxy.class); ScriptType type = randomFrom(ScriptType.values()); Map params = Collections.emptyMap(); @@ -120,8 +115,7 @@ public class ScriptTransformTests extends ESTestCase { assertThat(result.reason(), containsString("_error")); } - @Test - public void testExecute_NonMapValue() throws Exception { + public void testExecuteNonMapValue() throws Exception { ScriptServiceProxy service = mock(ScriptServiceProxy.class); ScriptType type = randomFrom(ScriptType.values()); @@ -149,7 +143,6 @@ public class ScriptTransformTests extends ESTestCase { assertThat(result.payload().data(), hasEntry("_value", value)); } - @Test public void testParser() throws Exception { ScriptServiceProxy service = mock(ScriptServiceProxy.class); ScriptType type = randomFrom(ScriptType.values()); @@ -166,8 +159,7 @@ public class ScriptTransformTests extends ESTestCase { assertThat(transform.transform().getScript(), equalTo(script)); } - @Test - public void testParser_String() throws Exception { + public void testParserString() throws Exception { ScriptServiceProxy service = mock(ScriptServiceProxy.class); XContentBuilder builder = jsonBuilder().value("_script"); @@ -177,9 +169,7 @@ public class ScriptTransformTests extends ESTestCase { assertThat(transform.transform().getScript(), equalTo(Script.defaultType("_script").build())); } - - @Test(expected = ScriptException.class) - public void testScriptConditionParser_badScript() throws Exception { + public void testScriptConditionParserBadScript() throws Exception { ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); ScriptType scriptType = randomFrom(ScriptType.values()); String script; @@ -202,12 +192,16 @@ public class ScriptTransformTests extends ESTestCase { XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptTransform scriptTransform = transformFactory.parseTransform("_watch", parser); - transformFactory.createExecutable(scriptTransform); - fail("expected a transform validation exception trying to create an executable with a bad or missing script"); + try { + transformFactory.createExecutable(scriptTransform); + fail("expected a transform validation exception trying to create an executable with a bad or missing script"); + } catch (ScriptException e) { + // I don't think this is what this test intended to check! + assertThat(e.getMessage(), containsString("script_lang not supported [groovy]")); + } } - @Test(expected = ScriptException.class) - public void testScriptConditionParser_badLang() throws Exception { + public void testScriptConditionParserBadLang() throws Exception { ScriptTransformFactory transformFactory = new ScriptTransformFactory(Settings.settingsBuilder().build(), getScriptServiceProxy(tp)); ScriptType scriptType = randomFrom(ScriptType.values()); String script = "return true"; @@ -221,8 +215,12 @@ public class ScriptTransformTests extends ESTestCase { XContentParser parser = XContentFactory.xContent(builder.bytes()).createParser(builder.bytes()); parser.nextToken(); ScriptTransform scriptCondition = transformFactory.parseTransform("_watch", parser); - transformFactory.createExecutable(scriptCondition); - fail("expected a transform validation exception trying to create an executable with an invalid language"); + try { + transformFactory.createExecutable(scriptCondition); + fail("expected a transform validation exception trying to create an executable with an invalid language"); + } catch (ScriptException e) { + assertThat(e.getMessage(), containsString("script_lang not supported [not_a_valid_lang]")); + } } static Script.Builder scriptBuilder(ScriptType type, String script) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java index 474ceb233b7..a975cf2cd91 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transform/search/SearchTransformTests.java @@ -6,6 +6,7 @@ package org.elasticsearch.watcher.transform.search; import com.google.common.base.Charsets; + import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; @@ -16,7 +17,10 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.*; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentFactory; +import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.query.QueryBuilders; @@ -45,7 +49,6 @@ import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStatus; import org.joda.time.DateTime; import org.joda.time.chrono.ISOChronology; -import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -60,12 +63,25 @@ import static java.util.Collections.emptyMap; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; import static org.elasticsearch.watcher.support.WatcherDateTimeUtils.parseDate; -import static org.elasticsearch.watcher.test.WatcherTestUtils.*; -import static org.hamcrest.Matchers.*; +import static org.elasticsearch.watcher.test.WatcherTestUtils.EMPTY_PAYLOAD; +import static org.elasticsearch.watcher.test.WatcherTestUtils.getRandomSupportedSearchType; +import static org.elasticsearch.watcher.test.WatcherTestUtils.mockExecutionContext; +import static org.elasticsearch.watcher.test.WatcherTestUtils.simplePayload; +import static org.hamcrest.Matchers.arrayContainingInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.joda.time.DateTimeZone.UTC; /** @@ -73,7 +89,6 @@ import static org.joda.time.DateTimeZone.UTC; */ @ClusterScope(scope = SUITE, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 1) public class SearchTransformTests extends ESIntegTestCase { - @Override public Settings nodeSettings(int nodeOrdinal) { final Path tempDir = createTempDir(); @@ -117,9 +132,7 @@ public class SearchTransformTests extends ESIntegTestCase { .build(); } - @Test public void testExecute() throws Exception { - index("idx", "type", "1"); ensureGreen("idx"); refresh(); @@ -149,9 +162,7 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(resultData, equalTo(expectedData)); } - @Test - public void testExecute_Failure() throws Exception { - + public void testExecuteFailure() throws Exception { index("idx", "type", "1"); ensureGreen("idx"); refresh(); @@ -192,8 +203,7 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(decodedQuery, containsString("_unknown_query_")); } - @Test - public void testExecute_MustacheTemplate() throws Exception { + public void testExecuteMustacheTemplate() throws Exception { // The rational behind this test: // @@ -256,7 +266,6 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(resultData, equalTo(expectedData)); } - @Test public void testParser() throws Exception { String[] indices = rarely() ? null : randomBoolean() ? new String[] { "idx" } : new String[] { "idx1", "idx2" }; SearchType searchType = getRandomSupportedSearchType(); @@ -313,8 +322,7 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(executable.transform().getTimeout(), equalTo(readTimeout)); } - @Test - public void testSearch_InlineTemplate() throws Exception { + public void testSearchInlineTemplate() throws Exception { WatchExecutionContext ctx = createContext(); final String templateQuery = "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"event_type\":{\"query\":\"a\"," + @@ -355,8 +363,7 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(executedResult.executedRequest().template(), equalTo(expectedTemplate)); } - @Test - public void testSearch_IndexedTemplate() throws Exception { + public void testSearchIndexedTemplate() throws Exception { WatchExecutionContext ctx = createContext(); final String templateQuery = "{\"query\":{\"bool\":{\"must\":[{\"match\":{\"event_type\":{\"query\":\"a\"," + @@ -390,8 +397,7 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(resultTemplate.getType(), equalTo(ScriptType.INDEXED)); } - @Test - public void testSearch_OndiskTemplate() throws Exception { + public void testSearchOnDiskTemplate() throws Exception { WatchExecutionContext ctx = createContext(); Map params = new HashMap<>(); @@ -409,8 +415,6 @@ public class SearchTransformTests extends ESIntegTestCase { assertThat(resultTemplate.getType(), equalTo(ScriptType.FILE)); } - - @Test public void testDifferentSearchType() throws Exception { WatchExecutionContext ctx = createContext(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/ack/WatchAckTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/ack/WatchAckTests.java index 58b6a210f14..b3a3f5a1468 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/ack/WatchAckTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/ack/WatchAckTests.java @@ -27,7 +27,6 @@ import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.watch.Watch; import org.elasticsearch.watcher.watch.WatchStore; import org.hamcrest.Matchers; -import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -41,14 +40,16 @@ import static org.elasticsearch.watcher.test.WatcherTestUtils.matchAllRequest; import static org.elasticsearch.watcher.transform.TransformBuilders.searchTransform; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsEqual.equalTo; /** */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class WatchAckTests extends AbstractWatcherIntegrationTestCase { - private IndexResponse indexTestDoc() { createIndex("actions", "events"); ensureGreen("actions", "events"); @@ -61,8 +62,7 @@ public class WatchAckTests extends AbstractWatcherIntegrationTestCase { return eventIndexResponse; } - @Test - public void testAck_SingleAction() throws Exception { + public void testAckSingleAction() throws Exception { WatcherClient watcherClient = watcherClient(); IndexResponse eventIndexResponse = indexTestDoc(); @@ -134,8 +134,7 @@ public class WatchAckTests extends AbstractWatcherIntegrationTestCase { assertThat(throttledCount, greaterThan(0L)); } - @Test - public void testAck_AllActions() throws Exception { + public void testAckAllActions() throws Exception { WatcherClient watcherClient = watcherClient(); IndexResponse eventIndexResponse = indexTestDoc(); @@ -215,8 +214,7 @@ public class WatchAckTests extends AbstractWatcherIntegrationTestCase { assertThat(throttledCount, greaterThan(0L)); } - @Test - public void testAck_WithRestart() throws Exception { + public void testAckWithRestart() throws Exception { WatcherClient watcherClient = watcherClient(); indexTestDoc(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() @@ -278,15 +276,23 @@ public class WatchAckTests extends AbstractWatcherIntegrationTestCase { assertThat(countAfterPostAckFires, equalTo(countAfterAck)); } - @Test(expected = ActionRequestValidationException.class) - public void testAck_InvalidWatchId() throws Exception { + public void testAckInvalidWatchId() throws Exception { WatcherClient watcherClient = watcherClient(); - watcherClient.prepareAckWatch("id with whitespaces").get(); + try { + watcherClient.prepareAckWatch("id with whitespaces").get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } - @Test(expected = ActionRequestValidationException.class) - public void testAck_InvalidActionId() throws Exception { + public void testAckInvalidActionId() throws Exception { WatcherClient watcherClient = watcherClient(); - watcherClient.prepareAckWatch("_id").setActionIds("id with whitespaces").get(); + try { + watcherClient.prepareAckWatch("_id").setActionIds("id with whitespaces").get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/activate/ActivateWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/activate/ActivateWatchTests.java index 6e852ea8fc1..2ec3e49c710 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/activate/ActivateWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/activate/ActivateWatchTests.java @@ -20,7 +20,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.activate.ActivateWatchResponse; import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -32,18 +31,18 @@ import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** */ public class ActivateWatchTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return false; } - @Test public void testDeactivateAndActivate() throws Exception { WatcherClient watcherClient = watcherClient(); @@ -101,7 +100,6 @@ public class ActivateWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(count3, greaterThan(count1)); } - @Test public void testLoadWatchWithoutAState() throws Exception { WatcherClient watcherClient = watcherClient(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/DeleteWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/DeleteWatchTests.java index 4e65298fa6c..8ca38d4ff47 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/DeleteWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/DeleteWatchTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchRequest; import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; @@ -18,6 +17,7 @@ import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondit import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -25,8 +25,6 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class DeleteWatchTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testDelete() throws Exception { ensureWatcherStarted(); PutWatchResponse putResponse = watcherClient().preparePutWatch("_name").setSource(watchBuilder() @@ -46,8 +44,7 @@ public class DeleteWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(deleteResponse.isFound(), is(true)); } - @Test - public void testDelete_NotFound() throws Exception { + public void testDeleteNotFound() throws Exception { DeleteWatchResponse response = watcherClient().deleteWatch(new DeleteWatchRequest("_name")).get(); assertThat(response, notNullValue()); assertThat(response.getId(), is("_name")); @@ -55,9 +52,12 @@ public class DeleteWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(response.isFound(), is(false)); } - @Test(expected = ActionRequestValidationException.class) - public void testDelete_InvalidWatchId() throws Exception { - watcherClient().deleteWatch(new DeleteWatchRequest("id with whitespaces")).actionGet(); + public void testDeleteInvalidWatchId() throws Exception { + try { + watcherClient().deleteWatch(new DeleteWatchRequest("id with whitespaces")).actionGet(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/ForceDeleteWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/ForceDeleteWatchTests.java index f49bc73231d..379671420ef 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/ForceDeleteWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/delete/ForceDeleteWatchTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.elasticsearch.watcher.transport.actions.service.WatcherServiceResponse; -import org.junit.Test; import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; @@ -26,8 +25,8 @@ import static org.hamcrest.Matchers.is; */ @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class ForceDeleteWatchTests extends AbstractWatcherIntegrationTestCase { - //Disable time warping for the force delete long running watch test + @Override protected boolean timeWarped() { return false; } @@ -37,8 +36,8 @@ public class ForceDeleteWatchTests extends AbstractWatcherIntegrationTestCase { return false; } - @Test @TestLogging("_root:DEBUG") - public void testForceDelete_LongRunningWatch() throws Exception { + @TestLogging("_root:DEBUG") + public void testForceDeleteLongRunningWatch() throws Exception { PutWatchResponse putResponse = watcherClient().preparePutWatch("_name").setSource(watchBuilder() .trigger(schedule(interval("3s"))) .condition(scriptCondition(Script.inline("sleep 5000; return true"))) @@ -59,5 +58,4 @@ public class ForceDeleteWatchTests extends AbstractWatcherIntegrationTestCase { deleteWatchResponse = watcherClient().prepareDeleteWatch("_name").get(); assertThat(deleteWatchResponse.isFound(), is(false)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java index b632b57c926..e1e83b5bfdc 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchTests.java @@ -24,7 +24,6 @@ import org.elasticsearch.watcher.trigger.schedule.ScheduleTriggerEvent; import org.elasticsearch.watcher.watch.WatchStatus; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.junit.Test; import java.util.HashMap; import java.util.Map; @@ -38,6 +37,7 @@ import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.cron; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -46,27 +46,32 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { - - - @Test(expected = ActionRequestValidationException.class) - public void testExecute_InvalidWatchId() throws Exception { + public void testExecuteInvalidWatchId() throws Exception { DateTime now = DateTime.now(DateTimeZone.UTC); - watcherClient().prepareExecuteWatch("id with whitespaces") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .get(); + try { + watcherClient().prepareExecuteWatch("id with whitespaces") + .setTriggerEvent(new ScheduleTriggerEvent(now, now)) + .get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } - @Test(expected = ActionRequestValidationException.class) - public void testExecute_InvalidActionId() throws Exception { + public void testExecuteInvalidActionId() throws Exception { DateTime now = DateTime.now(DateTimeZone.UTC); - watcherClient().prepareExecuteWatch("_id") - .setTriggerEvent(new ScheduleTriggerEvent(now, now)) - .setActionMode("id with whitespaces", randomFrom(ActionExecutionMode.values())) - .get(); + try { + watcherClient().prepareExecuteWatch("_id") + .setTriggerEvent(new ScheduleTriggerEvent(now, now)) + .setActionMode("id with whitespaces", randomFrom(ActionExecutionMode.values())) + .get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Action id cannot have white spaces")); + } } - @Test - public void testExecute_AllDefaults() throws Exception { + public void testExecuteAllDefaults() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() @@ -107,8 +112,7 @@ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { assertValue(record, "result.actions.0.logging.logged_text", is("_text")); } - @Test - public void testExecute_CustomTriggerData() throws Exception { + public void testExecuteCustomTriggerData() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() @@ -164,8 +168,7 @@ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { assertValue(record, "result.actions.0.logging.logged_text", is("_text")); } - @Test - public void testExecute_AlternativeInput() throws Exception { + public void testExecuteAlternativeInput() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() @@ -208,8 +211,7 @@ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { assertValue(record, "result.actions.0.logging.logged_text", is("_text")); } - @Test - public void testExecute_IgnoreCondition() throws Exception { + public void testExecuteIgnoreCondition() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() @@ -253,8 +255,7 @@ public class ExecuteWatchTests extends AbstractWatcherIntegrationTestCase { assertValue(record, "result.actions.0.logging.logged_text", is("_text")); } - @Test - public void testExecute_ActionMode() throws Exception { + public void testExecuteActionMode() throws Exception { final WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java index bc03a5a8204..81f0b174caf 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/execute/ExecuteWatchWithDateMathTests.java @@ -13,7 +13,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.execute.ExecuteWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; import org.joda.time.DateTime; -import org.junit.Test; import java.util.HashMap; import java.util.Map; @@ -31,14 +30,12 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class ExecuteWatchWithDateMathTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return true; } - @Test - public void testExecute_CustomTriggerData() throws Exception { + public void testExecuteCustomTriggerData() throws Exception { WatcherClient watcherClient = watcherClient(); PutWatchResponse putWatchResponse = watcherClient.preparePutWatch() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/get/GetWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/get/GetWatchTests.java index 01f4ac27481..3333207ca4a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/get/GetWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/get/GetWatchTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.get.GetWatchRequest; import org.elasticsearch.watcher.transport.actions.get.GetWatchResponse; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import java.util.Map; @@ -21,15 +20,17 @@ import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondit import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; /** * */ public class GetWatchTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testGet() throws Exception { PutWatchResponse putResponse = watcherClient().preparePutWatch("_name").setSource(watchBuilder() .trigger(schedule(interval("5m"))) @@ -55,13 +56,16 @@ public class GetWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(source, not(hasKey("status"))); } - @Test(expected = ActionRequestValidationException.class) - public void testGet_InvalidWatchId() throws Exception { - watcherClient().prepareGetWatch("id with whitespaces").get(); + public void testGetInvalidWatchId() throws Exception { + try { + watcherClient().prepareGetWatch("id with whitespaces").get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } - @Test - public void testGet_NotFound() throws Exception { + public void testGetNotFound() throws Exception { GetWatchResponse getResponse = watcherClient().getWatch(new GetWatchRequest("_name")).get(); assertThat(getResponse, notNullValue()); assertThat(getResponse.getId(), is("_name")); @@ -71,5 +75,4 @@ public class GetWatchTests extends AbstractWatcherIntegrationTestCase { XContentSource source = getResponse.getSource(); assertThat(source, nullValue()); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/put/PutWatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/put/PutWatchTests.java index 44170483bbe..369de9086ce 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/put/PutWatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/put/PutWatchTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.watcher.client.WatchSourceBuilder; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.put.PutWatchResponse; -import org.junit.Test; import static org.elasticsearch.watcher.actions.ActionBuilders.loggingAction; import static org.elasticsearch.watcher.client.WatchSourceBuilders.watchBuilder; @@ -19,6 +18,7 @@ import static org.elasticsearch.watcher.condition.ConditionBuilders.alwaysCondit import static org.elasticsearch.watcher.input.InputBuilders.simpleInput; import static org.elasticsearch.watcher.trigger.TriggerBuilders.schedule; import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -26,9 +26,6 @@ import static org.hamcrest.Matchers.notNullValue; * */ public class PutWatchTests extends AbstractWatcherIntegrationTestCase { - - @Test - public void testPut() throws Exception { ensureWatcherStarted(); @@ -52,32 +49,42 @@ public class PutWatchTests extends AbstractWatcherIntegrationTestCase { assertThat(response.getVersion(), is(1L)); } - @Test(expected = IllegalStateException.class) - public void testPut_NoTrigger() throws Exception { + public void testPutNoTrigger() throws Exception { ensureWatcherStarted(); - watcherClient().preparePutWatch("_name").setSource(watchBuilder() - .input(simpleInput()) - .condition(alwaysCondition()) - .addAction("_action1", loggingAction("{{ctx.watch_id}}"))) - .get(); + try { + watcherClient().preparePutWatch("_name").setSource(watchBuilder() + .input(simpleInput()) + .condition(alwaysCondition()) + .addAction("_action1", loggingAction("{{ctx.watch_id}}"))) + .get(); + fail("Expected IllegalStateException"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("failed to build watch source. no trigger defined")); + } } - @Test(expected = ActionRequestValidationException.class) - public void testPut_InvalidWatchId() throws Exception { + public void testPutInvalidWatchId() throws Exception { ensureWatcherStarted(); - watcherClient().preparePutWatch("id with whitespaces").setSource(watchBuilder() - .trigger(schedule(interval("5m")))) - .get(); + try { + watcherClient().preparePutWatch("id with whitespaces").setSource(watchBuilder() + .trigger(schedule(interval("5m")))) + .get(); + fail("Expected ActionRequestValidationException"); + } catch (ActionRequestValidationException e) { + assertThat(e.getMessage(), containsString("Watch id cannot have white spaces")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testPut_InvalidActionId() throws Exception { + public void testPutInvalidActionId() throws Exception { ensureWatcherStarted(); - watcherClient().preparePutWatch("_name").setSource(watchBuilder() - .trigger(schedule(interval("5m"))) - .addAction("id with whitespaces", loggingAction("{{ctx.watch_id}}"))) - .get(); + try { + watcherClient().preparePutWatch("_name").setSource(watchBuilder() + .trigger(schedule(interval("5m"))) + .addAction("id with whitespaces", loggingAction("{{ctx.watch_id}}"))) + .get(); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("Action id cannot have white spaces")); + } } - - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/SlowWatchStatsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/SlowWatchStatsTests.java index 0c730a5f72f..8beef6d405e 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/SlowWatchStatsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/SlowWatchStatsTests.java @@ -18,7 +18,6 @@ import org.elasticsearch.watcher.input.InputBuilders; import org.elasticsearch.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; import org.joda.time.DateTime; -import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -36,7 +35,6 @@ import static org.hamcrest.Matchers.nullValue; @ESIntegTestCase.ClusterScope(scope = TEST, numClientNodes = 0, transportClientRatio = 0, randomDynamicTemplates = false, numDataNodes = 2) @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class SlowWatchStatsTests extends AbstractWatcherIntegrationTestCase { - @Override protected boolean timeWarped() { return false; @@ -51,7 +49,6 @@ public class SlowWatchStatsTests extends AbstractWatcherIntegrationTestCase { .build(); } - @Test public void testCurrentWatches() throws Exception { watcherClient().preparePutWatch("_id").setSource(watchBuilder() .trigger(schedule(interval("1s"))) @@ -75,7 +72,6 @@ public class SlowWatchStatsTests extends AbstractWatcherIntegrationTestCase { }); } - @Test public void testPendingWatches() throws Exception { // Add 5 slow watches and we should almost immediately see pending watches in the stats api for (int i = 0; i < 5; i++) { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/WatcherStatsTests.java b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/WatcherStatsTests.java index 032a3cd3753..49cb17ca7d3 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/WatcherStatsTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/transport/action/stats/WatcherStatsTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.watcher.test.WatcherTestUtils; import org.elasticsearch.watcher.transport.actions.delete.DeleteWatchResponse; import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsRequest; import org.elasticsearch.watcher.transport.actions.stats.WatcherStatsResponse; -import org.junit.Test; import java.util.concurrent.TimeUnit; @@ -41,8 +40,6 @@ import static org.hamcrest.core.IsEqual.equalTo; @TestLogging("watcher:TRACE") @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/724") public class WatcherStatsTests extends AbstractWatcherIntegrationTestCase { - - @Test public void testStartedStats() throws Exception { WatcherStatsRequest watcherStatsRequest = watcherClient().prepareWatcherStats().request(); WatcherStatsResponse response = watcherClient().watcherStats(watcherStatsRequest).actionGet(); @@ -54,7 +51,6 @@ public class WatcherStatsTests extends AbstractWatcherIntegrationTestCase { assertThat(response.getBuild(), is(WatcherBuild.CURRENT)); } - @Test public void testWatchCountStats() throws Exception { WatcherClient watcherClient = watcherClient(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/CronScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/CronScheduleTests.java index 3bae1fb3299..c0ba680a3e9 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/CronScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/CronScheduleTests.java @@ -10,24 +10,27 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; /** * */ public class CronScheduleTests extends ScheduleTestCase { - - @Test(expected = IllegalArgumentException.class) public void testInvalid() throws Exception { - new CronSchedule("0 * * *"); - fail("expecting a validation error to be thrown when creating a cron schedule with invalid cron expression"); + try { + new CronSchedule("0 * * *"); + fail("expecting a validation error to be thrown when creating a cron schedule with invalid cron expression"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), is("invalid cron expression [0 * * *]")); + } } - @Test - public void testParse_Single() throws Exception { + public void testParseSingle() throws Exception { XContentBuilder builder = jsonBuilder().value("0 0/5 * * * ?"); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -37,8 +40,7 @@ public class CronScheduleTests extends ScheduleTestCase { assertThat(schedule.crons()[0].expression(), is("0 0/5 * * * ?")); } - @Test - public void testParse_Multiple() throws Exception { + public void testParseMultiple() throws Exception { XContentBuilder builder = jsonBuilder().value(new String[] { "0 0/1 * * * ?", "0 0/2 * * * ?", @@ -55,8 +57,7 @@ public class CronScheduleTests extends ScheduleTestCase { assertThat(crons, hasItemInArray("0 0/3 * * * ?")); } - @Test - public void testParse_Invalid_BadExpression() throws Exception { + public void testParseInvalidBadExpression() throws Exception { XContentBuilder builder = jsonBuilder().value("0 0/5 * * ?"); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -70,30 +71,42 @@ public class CronScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_Invalid_Empty() throws Exception { + public void testParseInvalidEmpty() throws Exception { XContentBuilder builder = jsonBuilder(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - new CronSchedule.Parser().parse(parser); + try { + new CronSchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [cron] schedule. expected either a cron string value or an array of cron string values, but found [null]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_Invalid_Object() throws Exception { + public void testParseInvalidObject() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - new CronSchedule.Parser().parse(parser); + try { + new CronSchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [cron] schedule. expected either a cron string value or an array of cron string values, but found [START_OBJECT]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_Invalid_EmptyArray() throws Exception { + public void testParseInvalidEmptyArray() throws Exception { XContentBuilder builder = jsonBuilder().value(new String[0]); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); - new CronSchedule.Parser().parse(parser); + try { + new CronSchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [cron] schedule. no cron expression found in cron array")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/DailyScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/DailyScheduleTests.java index a0fdd138f63..cd08fd033a6 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/DailyScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/DailyScheduleTests.java @@ -11,27 +11,29 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.watcher.trigger.schedule.support.DayTimes; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Strings.join; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.either; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class DailyScheduleTests extends ScheduleTestCase { - - @Test - public void test_Default() throws Exception { + public void testDefault() throws Exception { DailySchedule schedule = new DailySchedule(); String[] crons = expressions(schedule.crons()); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 0 * * ?")); } - @Test - public void test_SingleTime() throws Exception { + public void testSingleTime() throws Exception { DayTimes time = validDayTime(); DailySchedule schedule = new DailySchedule(time); String[] crons = expressions(schedule); @@ -39,15 +41,18 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(crons, arrayContaining("0 " + join(",", time.minute()) + " " + join(",", time.hour()) + " * * ?")); } - @Test(expected = IllegalArgumentException.class) - public void test_SingleTime_Invalid() throws Exception { + public void testSingleTimeInvalid() throws Exception { HourAndMinute ham = invalidDayTime(); - new DayTimes(ham.hour, ham.minute); - fail("expected an illegal argument exception on invalid time input"); + try { + new DayTimes(ham.hour, ham.minute); + fail("expected an illegal argument exception on invalid time input"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("invalid time [")); + assertThat(e.getMessage(), either(containsString("invalid time hour value")).or(containsString("invalid time minute value"))); + } } - @Test - public void test_MultipleTimes() throws Exception { + public void testMultipleTimes() throws Exception { DayTimes[] times = validDayTimes(); DailySchedule schedule = new DailySchedule(times); String[] crons = expressions(schedule); @@ -57,8 +62,7 @@ public class DailyScheduleTests extends ScheduleTestCase { } } - @Test - public void testParser_Empty() throws Exception { + public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -69,8 +73,7 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(new DayTimes(0, 0))); } - @Test - public void testParser_SingleTime_Object() throws Exception { + public void testParserSingleTimeObject() throws Exception { DayTimes time = validDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -88,8 +91,7 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(time)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleTime_Object_Invalid() throws Exception { + public void testParserSingleTimeObjectInvalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -101,11 +103,15 @@ public class DailyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new DailySchedule.Parser().parse(parser); + try { + new DailySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [START_OBJECT]")); + } } - @Test - public void testParser_SingleTime_String() throws Exception { + public void testParserSingleTimeString() throws Exception { String timeStr = validDayTimeStr(); XContentBuilder builder = jsonBuilder() .startObject() @@ -120,8 +126,7 @@ public class DailyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(DayTimes.parse(timeStr))); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleTime_String_Invalid() throws Exception { + public void testParserSingleTimeStringInvalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() .field("at", invalidDayTimeStr()) @@ -129,11 +134,15 @@ public class DailyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new DailySchedule.Parser().parse(parser); + try { + new DailySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [VALUE_STRING]")); + } } - @Test - public void testParser_MultipleTimes_Objects() throws Exception { + public void testParserMultipleTimesObjects() throws Exception { DayTimes[] times = validDayTimesFromNumbers(); XContentBuilder builder = jsonBuilder() .startObject() @@ -150,8 +159,7 @@ public class DailyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleTimes_Objects_Invalid() throws Exception { + public void testParserMultipleTimesObjectsInvalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -160,11 +168,15 @@ public class DailyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new DailySchedule.Parser().parse(parser); + try { + new DailySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [START_OBJECT]")); + } } - @Test - public void testParser_MultipleTimes_Strings() throws Exception { + public void testParserMultipleTimesStrings() throws Exception { DayTimes[] times = validDayTimesFromStrings(); XContentBuilder builder = jsonBuilder() .startObject() @@ -181,8 +193,7 @@ public class DailyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleTimes_Strings_Invalid() throws Exception { + public void testParserMultipleTimesStringsInvalid() throws Exception { String[] times = invalidDayTimesAsStrings(); XContentBuilder builder = jsonBuilder() .startObject() @@ -191,7 +202,11 @@ public class DailyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new DailySchedule.Parser().parse(parser); + try { + new DailySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [VALUE_STRING]")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/HourlyScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/HourlyScheduleTests.java index 9ddedc96fb8..836e749ce6a 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/HourlyScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/HourlyScheduleTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.watcher.support.Strings; -import org.junit.Test; import java.util.Arrays; import java.util.stream.Collectors; @@ -19,23 +18,24 @@ import java.util.stream.Collectors; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Integers.asIterable; import static org.elasticsearch.watcher.support.Integers.contains; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class HourlyScheduleTests extends ScheduleTestCase { - - @Test - public void test_Default() throws Exception { + public void testDefault() throws Exception { HourlySchedule schedule = new HourlySchedule(); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 * * * ?")); } - @Test - public void test_SingleMinute() throws Exception { + public void testSingleMinute() throws Exception { int minute = validMinute(); HourlySchedule schedule = new HourlySchedule(minute); String[] crons = expressions(schedule); @@ -43,13 +43,17 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(crons, arrayContaining("0 " + minute + " * * * ?")); } - @Test(expected = IllegalArgumentException.class) - public void test_SingleMinute_Invalid() throws Exception { - new HourlySchedule(invalidMinute()); + public void testSingleMinuteInvalid() throws Exception { + try { + new HourlySchedule(invalidMinute()); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("invalid hourly minute")); + assertThat(e.getMessage(), containsString("minute must be between 0 and 59 incl.")); + } } - @Test - public void test_MultipleMinutes() throws Exception { + public void testMultipleMinutes() throws Exception { int[] minutes = validMinutes(); String minutesStr = Strings.join(",", minutes); HourlySchedule schedule = new HourlySchedule(minutes); @@ -58,14 +62,18 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(crons, arrayContaining("0 " + minutesStr + " * * * ?")); } - @Test(expected = IllegalArgumentException.class) - public void test_MultipleMinutes_Invalid() throws Exception { + public void testMultipleMinutesInvalid() throws Exception { int[] minutes = invalidMinutes(); - new HourlySchedule(minutes); + try { + new HourlySchedule(minutes); + fail("Expected IllegalArgumentException"); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage(), containsString("invalid hourly minute")); + assertThat(e.getMessage(), containsString("minute must be between 0 and 59 incl.")); + } } - @Test - public void testParser_Empty() throws Exception { + public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -76,8 +84,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule.minutes()[0], is(0)); } - @Test - public void testParser_SingleMinute_Number() throws Exception { + public void testParserSingleMinuteNumber() throws Exception { int minute = validMinute(); XContentBuilder builder = jsonBuilder() .startObject() @@ -92,8 +99,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule.minutes()[0], is(minute)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleMinute_Number_Invalid() throws Exception { + public void testParserSingleMinuteNumberInvalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() .field("minute", invalidMinute()) @@ -101,11 +107,15 @@ public class HourlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new HourlySchedule.Parser().parse(parser); + try { + new HourlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [hourly] schedule. invalid value for [minute]")); + } } - @Test - public void testParser_SingleMinute_String() throws Exception { + public void testParserSingleMinuteString() throws Exception { int minute = validMinute(); XContentBuilder builder = jsonBuilder() .startObject() @@ -120,8 +130,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule.minutes()[0], is(minute)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleMinute_String_Invalid() throws Exception { + public void testParserSingleMinuteStringInvalid() throws Exception { XContentBuilder builder = jsonBuilder() .startObject() .field("minute", String.valueOf(invalidMinute())) @@ -129,11 +138,15 @@ public class HourlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new HourlySchedule.Parser().parse(parser); + try { + new HourlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [hourly] schedule. invalid value for [minute]")); + } } - @Test - public void testParser_MultipleMinutes_Numbers() throws Exception { + public void testParserMultipleMinutesNumbers() throws Exception { int[] minutes = validMinutes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -146,13 +159,11 @@ public class HourlyScheduleTests extends ScheduleTestCase { assertThat(schedule, notNullValue()); assertThat(schedule.minutes().length, is(minutes.length)); for (int i = 0; i < minutes.length; i++) { - final int minute = minutes[i]; assertThat(contains(schedule.minutes(), minutes[i]), is(true)); } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleMinutes_Numbers_Invalid() throws Exception { + public void testParserMultipleMinutesNumbersInvalid() throws Exception { int[] minutes = invalidMinutes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -161,11 +172,15 @@ public class HourlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new HourlySchedule.Parser().parse(parser); + try { + new HourlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [hourly] schedule. invalid value for [minute]")); + } } - @Test - public void testParser_MultipleMinutes_Strings() throws Exception { + public void testParserMultipleMinutesStrings() throws Exception { int[] minutes = validMinutes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -182,8 +197,7 @@ public class HourlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleMinutes_Strings_Invalid() throws Exception { + public void testParserMultipleMinutesStringsInvalid() throws Exception { int[] minutes = invalidMinutes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -192,7 +206,11 @@ public class HourlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new HourlySchedule.Parser().parse(parser); + try { + new HourlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [hourly] schedule. invalid value for [minute]")); + } } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/IntervalScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/IntervalScheduleTests.java index fb5e633c11f..0091efd1d84 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/IntervalScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/IntervalScheduleTests.java @@ -11,19 +11,19 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class IntervalScheduleTests extends ESTestCase { - - @Test - public void testParse_Number() throws Exception { - long value = (long) randomIntBetween(0, Integer.MAX_VALUE); + public void testParseNumber() throws Exception { + long value = randomIntBetween(0, Integer.MAX_VALUE); XContentBuilder builder = jsonBuilder().value(value); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -33,9 +33,8 @@ public class IntervalScheduleTests extends ESTestCase { assertThat(schedule.interval().seconds(), is(value)); } - @Test - public void testParse_NegativeNumber() throws Exception { - long value = (long) randomIntBetween(Integer.MIN_VALUE, 0); + public void testParseNegativeNumber() throws Exception { + long value = randomIntBetween(Integer.MIN_VALUE, 0); XContentBuilder builder = jsonBuilder().value(value); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -49,8 +48,7 @@ public class IntervalScheduleTests extends ESTestCase { } } - @Test - public void testParse_String() throws Exception { + public void testParseString() throws Exception { IntervalSchedule.Interval value = randomTimeInterval(); XContentBuilder builder = jsonBuilder().value(value); BytesReference bytes = builder.bytes(); @@ -61,22 +59,30 @@ public class IntervalScheduleTests extends ESTestCase { assertThat(schedule.interval(), is(value)); } - @Test(expected = ElasticsearchParseException.class) - public void testParse_Invalid_String() throws Exception { + public void testParseInvalidString() throws Exception { XContentBuilder builder = jsonBuilder().value("43S"); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new IntervalSchedule.Parser().parse(parser); + try { + new IntervalSchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("unrecognized interval format [43S]")); + } } - @Test(expected = ElasticsearchParseException.class) - public void testParse_Invalid_Object() throws Exception { + public void testParseInvalidObject() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new IntervalSchedule.Parser().parse(parser); + try { + new IntervalSchedule.Parser().parse(parser); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), containsString("expected either a numeric value (millis) or a string value representing time value")); + assertThat(e.getMessage(), containsString("found [START_OBJECT]")); + } } private static IntervalSchedule.Interval randomTimeInterval() { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/MonthlyScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/MonthlyScheduleTests.java index 46d391908e5..80d7c1c2ff9 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/MonthlyScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/MonthlyScheduleTests.java @@ -12,27 +12,27 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.watcher.trigger.schedule.support.DayTimes; import org.elasticsearch.watcher.trigger.schedule.support.MonthTimes; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Strings.join; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class MonthlyScheduleTests extends ScheduleTestCase { - - @Test - public void test_Default() throws Exception { + public void testDefault() throws Exception { MonthlySchedule schedule = new MonthlySchedule(); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 0 1 * ?")); } - @Test - public void test_SingleTime() throws Exception { + public void testSingleTime() throws Exception { MonthTimes time = validMonthTime(); MonthlySchedule schedule = new MonthlySchedule(time); String[] crons = expressions(schedule); @@ -46,8 +46,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { } } - @Test - public void test_MultipleTimes() throws Exception { + public void testMultipleTimes() throws Exception { MonthTimes[] times = validMonthTimes(); MonthlySchedule schedule = new MonthlySchedule(times); String[] crons = expressions(schedule); @@ -67,8 +66,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { } } - @Test - public void testParser_Empty() throws Exception { + public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -79,8 +77,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(new MonthTimes())); } - @Test - public void testParser_SingleTime() throws Exception { + public void testParserSingleTime() throws Exception { DayTimes time = validDayTime(); Object day = randomDayOfMonth(); XContentBuilder builder = jsonBuilder() @@ -103,8 +100,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleTime_Invalid() throws Exception { + public void testParserSingleTimeInvalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -117,11 +113,15 @@ public class MonthlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new MonthlySchedule.Parser().parse(parser); + try { + new MonthlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [monthly] schedule. invalid month times")); + } } - @Test - public void testParser_MultipleTimes() throws Exception { + public void testParserMultipleTimes() throws Exception { MonthTimes[] times = validMonthTimes(); XContentBuilder builder = jsonBuilder().value(times); BytesReference bytes = builder.bytes(); @@ -135,8 +135,7 @@ public class MonthlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleTimes_Invalid() throws Exception { + public void testParserMultipleTimesInvalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -146,6 +145,11 @@ public class MonthlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new MonthlySchedule.Parser().parse(parser); + try { + new MonthlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [monthly] schedule. invalid month times")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistryTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistryTests.java index 2579b36bcd9..7ffc9113b1d 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistryTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleRegistryTests.java @@ -11,19 +11,20 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.junit.Before; -import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class ScheduleRegistryTests extends ScheduleTestCase { - private ScheduleRegistry registry; @Before @@ -38,8 +39,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { registry = new ScheduleRegistry(parsers); } - @Test - public void testParser_Interval() throws Exception { + public void testParserInterval() throws Exception { IntervalSchedule interval = randomIntervalSchedule(); XContentBuilder builder = jsonBuilder() .startObject() @@ -54,8 +54,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { assertThat((IntervalSchedule) schedule, is(interval)); } - @Test - public void testParse_Cron() throws Exception { + public void testParseCron() throws Exception { Object cron = randomBoolean() ? Schedules.cron("* 0/5 * * * ?") : Schedules.cron("* 0/2 * * * ?", "* 0/3 * * * ?", "* 0/5 * * * ?"); @@ -72,8 +71,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { assertThat(schedule, is(cron)); } - @Test - public void testParse_Hourly() throws Exception { + public void testParseHourly() throws Exception { HourlySchedule hourly = randomHourlySchedule(); XContentBuilder builder = jsonBuilder() .startObject() @@ -88,8 +86,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { assertThat((HourlySchedule) schedule, equalTo(hourly)); } - @Test - public void testParse_Daily() throws Exception { + public void testParseDaily() throws Exception { DailySchedule daily = randomDailySchedule(); XContentBuilder builder = jsonBuilder() .startObject() @@ -104,8 +101,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { assertThat((DailySchedule) schedule, equalTo(daily)); } - @Test - public void testParse_Weekly() throws Exception { + public void testParseWeekly() throws Exception { WeeklySchedule weekly = randomWeeklySchedule(); XContentBuilder builder = jsonBuilder() .startObject() @@ -120,8 +116,7 @@ public class ScheduleRegistryTests extends ScheduleTestCase { assertThat((WeeklySchedule) schedule, equalTo(weekly)); } - @Test - public void testParse_Monthly() throws Exception { + public void testParseMonthly() throws Exception { MonthlySchedule monthly = randomMonthlySchedule(); XContentBuilder builder = jsonBuilder() .startObject() diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleTriggerEventTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleTriggerEventTests.java index 99c3a078f93..5f26c19c07d 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleTriggerEventTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/ScheduleTriggerEventTests.java @@ -12,17 +12,13 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.clock.SystemClock; -import org.junit.Test; import static org.hamcrest.Matchers.is; /** */ public class ScheduleTriggerEventTests extends ESTestCase { - - @Test - - public void testParser_RandomDateMath() throws Exception { + public void testParserRandomDateMath() throws Exception { String triggeredTime = randomFrom("now", "now+5m", "2015-05-07T22:24:41.254Z", "2015-05-07T22:24:41.254Z||-5m"); String scheduledTime = randomFrom("now", "now-5m", "2015-05-07T22:24:41.254Z", "2015-05-07T22:24:41.254Z||+5h"); XContentBuilder jsonBuilder = XContentFactory.jsonBuilder(); @@ -38,5 +34,4 @@ public class ScheduleTriggerEventTests extends ESTestCase { assertThat(scheduleTriggerEvent.scheduledTime().isAfter(0), is(true)); assertThat(scheduleTriggerEvent.triggeredTime().isAfter(0), is(true)); } - } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/WeeklyScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/WeeklyScheduleTests.java index d60b9b3feeb..de409d64579 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/WeeklyScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/WeeklyScheduleTests.java @@ -15,27 +15,29 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.watcher.trigger.schedule.support.DayOfWeek; import org.elasticsearch.watcher.trigger.schedule.support.DayTimes; import org.elasticsearch.watcher.trigger.schedule.support.WeekTimes; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Strings.join; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class WeeklyScheduleTests extends ScheduleTestCase { - - @Test - public void test_Default() throws Exception { + public void testDefault() throws Exception { WeeklySchedule schedule = new WeeklySchedule(); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 0 ? * MON")); } - @Test - public void test_SingleTime() throws Exception { + public void testSingleTime() throws Exception { WeekTimes time = validWeekTime(); WeeklySchedule schedule = new WeeklySchedule(time); String[] crons = expressions(schedule); @@ -45,8 +47,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { } } - @Test - public void test_MultipleTimes() throws Exception { + public void testMultipleTimes() throws Exception { WeekTimes[] times = validWeekTimes(); WeeklySchedule schedule = new WeeklySchedule(times); String[] crons = expressions(schedule); @@ -62,8 +63,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { } } - @Test - public void testParser_Empty() throws Exception { + public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -74,8 +74,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(new WeekTimes(DayOfWeek.MONDAY, new DayTimes()))); } - @Test - public void testParser_SingleTime() throws Exception { + public void testParserSingleTime() throws Exception { DayTimes time = validDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -97,8 +96,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleTime_Invalid() throws Exception { + public void testParserSingleTimeInvalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -111,11 +109,15 @@ public class WeeklyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new WeeklySchedule.Parser().parse(parser); + try { + new WeeklySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [weekly] schedule. invalid weekly times")); + } } - @Test - public void testParser_MultipleTimes() throws Exception { + public void testParserMultipleTimes() throws Exception { WeekTimes[] times = validWeekTimes(); XContentBuilder builder = jsonBuilder().value(times); BytesReference bytes = builder.bytes(); @@ -129,8 +131,7 @@ public class WeeklyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleTimes_Objects_Invalid() throws Exception { + public void testParserMultipleTimesObjectsInvalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -140,6 +141,11 @@ public class WeeklyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new WeeklySchedule.Parser().parse(parser); + try { + new WeeklySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [weekly] schedule. invalid weekly times")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/YearlyScheduleTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/YearlyScheduleTests.java index d4eb738e093..eb43bfc830d 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/YearlyScheduleTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/YearlyScheduleTests.java @@ -14,27 +14,27 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.watcher.trigger.schedule.support.DayTimes; import org.elasticsearch.watcher.trigger.schedule.support.YearTimes; -import org.junit.Test; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.watcher.support.Strings.join; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.arrayContaining; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.hasItemInArray; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; /** * */ public class YearlyScheduleTests extends ScheduleTestCase { - - @Test - public void test_Default() throws Exception { + public void testDefault() throws Exception { YearlySchedule schedule = new YearlySchedule(); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 0 1 JAN ?")); } - @Test - public void test_SingleTime() throws Exception { + public void testSingleTime() throws Exception { YearTimes time = validYearTime(); YearlySchedule schedule = new YearlySchedule(time); String[] crons = expressions(schedule); @@ -51,8 +51,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { } } - @Test - public void test_MultipleTimes() throws Exception { + public void testMultipleTimes() throws Exception { YearTimes[] times = validYearTimes(); YearlySchedule schedule = new YearlySchedule(times); String[] crons = expressions(schedule); @@ -73,8 +72,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { } } - @Test - public void testParser_Empty() throws Exception { + public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); @@ -85,8 +83,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0], is(new YearTimes())); } - @Test - public void testParser_SingleTime() throws Exception { + public void testParserSingleTime() throws Exception { DayTimes time = validDayTime(); Object day = randomDayOfMonth(); Object month = randomMonth(); @@ -111,8 +108,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { assertThat(schedule.times()[0].times(), hasItemInArray(time)); } - @Test(expected = ElasticsearchParseException.class) - public void testParser_SingleTime_Invalid() throws Exception { + public void testParserSingleTimeInvalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder() .startObject() @@ -126,11 +122,15 @@ public class YearlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new MonthlySchedule.Parser().parse(parser); + try { + new MonthlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [monthly] schedule. invalid month times")); + } } - @Test - public void testParser_MultipleTimes() throws Exception { + public void testParserMultipleTimes() throws Exception { YearTimes[] times = validYearTimes(); XContentBuilder builder = jsonBuilder().value(times); BytesReference bytes = builder.bytes(); @@ -144,8 +144,7 @@ public class YearlyScheduleTests extends ScheduleTestCase { } } - @Test(expected = ElasticsearchParseException.class) - public void testParser_MultipleTimes_Invalid() throws Exception { + public void testParserMultipleTimesInvalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder() .startObject() @@ -156,6 +155,11 @@ public class YearlyScheduleTests extends ScheduleTestCase { BytesReference bytes = builder.bytes(); XContentParser parser = JsonXContent.jsonXContent.createParser(bytes); parser.nextToken(); // advancing to the start object - new YearlySchedule.Parser().parse(parser); + try { + new YearlySchedule.Parser().parse(parser); + fail("Expected ElasticsearchParseException"); + } catch (ElasticsearchParseException e) { + assertThat(e.getMessage(), is("could not parse [yearly] schedule. invalid year times")); + } } } diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/engine/BaseTriggerEngineTestCase.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/engine/BaseTriggerEngineTestCase.java index 4231e983688..3a565e5e253 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/engine/BaseTriggerEngineTestCase.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/engine/BaseTriggerEngineTestCase.java @@ -17,7 +17,6 @@ import org.elasticsearch.watcher.trigger.schedule.support.WeekTimes; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.BitSet; @@ -26,12 +25,14 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.elasticsearch.watcher.trigger.schedule.Schedules.*; +import static org.elasticsearch.watcher.trigger.schedule.Schedules.daily; +import static org.elasticsearch.watcher.trigger.schedule.Schedules.hourly; +import static org.elasticsearch.watcher.trigger.schedule.Schedules.interval; +import static org.elasticsearch.watcher.trigger.schedule.Schedules.weekly; import static org.hamcrest.Matchers.is; import static org.joda.time.DateTimeZone.UTC; public abstract class BaseTriggerEngineTestCase extends ESTestCase { - private TriggerEngine engine; @Before @@ -46,7 +47,6 @@ public abstract class BaseTriggerEngineTestCase extends ESTestCase { engine.stop(); } - @Test public void testStart() throws Exception { int count = randomIntBetween(2, 5); final CountDownLatch latch = new CountDownLatch(count); @@ -79,8 +79,7 @@ public abstract class BaseTriggerEngineTestCase extends ESTestCase { assertThat(bits.cardinality(), is(count)); } - @Test - public void testAdd_Hourly() throws Exception { + public void testAddHourly() throws Exception { final String name = "job_name"; final CountDownLatch latch = new CountDownLatch(1); engine.start(Collections.emptySet()); @@ -113,8 +112,7 @@ public abstract class BaseTriggerEngineTestCase extends ESTestCase { } } - @Test - public void testAdd_Daily() throws Exception { + public void testAddDaily() throws Exception { final String name = "job_name"; final CountDownLatch latch = new CountDownLatch(1); engine.start(Collections.emptySet()); @@ -149,8 +147,7 @@ public abstract class BaseTriggerEngineTestCase extends ESTestCase { } } - @Test - public void testAdd_Weekly() throws Exception { + public void testAddWeekly() throws Exception { final String name = "job_name"; final CountDownLatch latch = new CountDownLatch(1); engine.start(Collections.emptySet()); @@ -187,7 +184,6 @@ public abstract class BaseTriggerEngineTestCase extends ESTestCase { } } - @Test public void testAddSameJobSeveralTimes() { engine.start(Collections.emptySet()); engine.register(new TriggerEngine.Listener() { diff --git a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/tool/CronEvalToolTests.java b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/tool/CronEvalToolTests.java index f1b0d7cfef8..c2d06d4be17 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/tool/CronEvalToolTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/trigger/schedule/tool/CronEvalToolTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.watcher.trigger.schedule.tool; import org.elasticsearch.common.cli.CliTool; import org.elasticsearch.common.cli.CliToolTestCase; -import org.junit.Test; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; @@ -16,8 +15,6 @@ import static org.hamcrest.Matchers.is; * */ public class CronEvalToolTests extends CliToolTestCase { - - @Test public void testParse() throws Exception { String countOption = randomBoolean() ? "-c" : "--count"; int count = randomIntBetween(1, 100); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java index fee798ea458..dbd7108dadd 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchLockServiceTests.java @@ -8,7 +8,6 @@ package org.elasticsearch.watcher.watch; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ESTestCase; -import org.junit.Test; import java.util.ArrayList; import java.util.List; @@ -16,14 +15,14 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; /** */ public class WatchLockServiceTests extends ESTestCase { - - @Test - public void testLocking_notStarted() { + public void testLockingNotStarted() { WatchLockService lockService = new WatchLockService(new TimeValue(1, TimeUnit.SECONDS)); try { lockService.acquire("_name"); @@ -33,7 +32,6 @@ public class WatchLockServiceTests extends ESTestCase { } } - @Test public void testLocking() { WatchLockService lockService = new WatchLockService(new TimeValue(1, TimeUnit.SECONDS)); lockService.start(); @@ -44,8 +42,7 @@ public class WatchLockServiceTests extends ESTestCase { lockService.stop(); } - @Test - public void testLocking_alreadyHeld() { + public void testLockingAlreadyHeld() { WatchLockService lockService = new WatchLockService(new TimeValue(1, TimeUnit.SECONDS)); lockService.start(); WatchLockService.Lock lock1 = lockService.acquire("_name"); @@ -59,17 +56,19 @@ public class WatchLockServiceTests extends ESTestCase { lockService.stop(); } - @Test(expected = ElasticsearchTimeoutException.class) - public void testLocking_stopTimeout(){ + public void testLockingStopTimeout(){ final WatchLockService lockService = new WatchLockService(new TimeValue(1, TimeUnit.SECONDS)); lockService.start(); lockService.acquire("_name"); - lockService.stop(); - fail(); + try { + lockService.stop(); + fail("Expected ElasticsearchTimeoutException"); + } catch (ElasticsearchTimeoutException e) { + assertThat(e.getMessage(), is("timed out waiting for watches to complete, after waiting for [2s]")); + } } - @Test - public void testLocking_fair() throws Exception { + public void testLockingFair() throws Exception { final WatchLockService lockService = new WatchLockService(new TimeValue(1, TimeUnit.SECONDS)); lockService.start(); final AtomicInteger value = new AtomicInteger(0); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java index 7f1dba418b9..7fe6cdc69ab 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchStoreTests.java @@ -5,19 +5,6 @@ */ package org.elasticsearch.watcher.watch; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import java.util.Collections; - import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; @@ -46,12 +33,23 @@ import org.elasticsearch.search.internal.InternalSearchHits; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.support.init.proxy.ClientProxy; import org.junit.Before; -import org.junit.Test; + +import java.util.Collections; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** */ public class WatchStoreTests extends ESTestCase { - private WatchStore watchStore; private ClientProxy clientProxy; private Watch.Parser parser; @@ -63,7 +61,6 @@ public class WatchStoreTests extends ESTestCase { watchStore = new WatchStore(Settings.EMPTY, clientProxy, parser); } - @Test public void testStartNoPreviousWatchesIndex() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); @@ -80,7 +77,6 @@ public class WatchStoreTests extends ESTestCase { verifyZeroInteractions(clientProxy); } - @Test public void testStartPrimaryShardNotReady() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); @@ -104,7 +100,6 @@ public class WatchStoreTests extends ESTestCase { verifyZeroInteractions(clientProxy); } - @Test public void testStartRefreshFailed() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); @@ -139,7 +134,6 @@ public class WatchStoreTests extends ESTestCase { verify(clientProxy, never()).clearScroll(anyString()); } - @Test public void testStartSearchFailed() { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); @@ -178,7 +172,6 @@ public class WatchStoreTests extends ESTestCase { verify(clientProxy, times(1)).clearScroll(anyString()); } - @Test public void testStartNoWatchStored() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); @@ -215,7 +208,6 @@ public class WatchStoreTests extends ESTestCase { verify(clientProxy, times(1)).clearScroll(anyString()); } - @Test public void testStartWatchStored() throws Exception { ClusterState.Builder csBuilder = new ClusterState.Builder(new ClusterName("_name")); MetaData.Builder metaDateBuilder = MetaData.builder(); diff --git a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java index f5b81dfd345..8e6ab9e37dc 100644 --- a/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java +++ b/watcher/src/test/java/org/elasticsearch/watcher/watch/WatchTests.java @@ -115,7 +115,6 @@ import org.elasticsearch.watcher.trigger.schedule.support.YearTimes; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; @@ -140,7 +139,6 @@ import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Mockito.mock; public class WatchTests extends ESTestCase { - private ScriptServiceProxy scriptService; private ClientProxy client; private HttpClient httpClient; @@ -167,8 +165,7 @@ public class WatchTests extends ESTestCase { logger = Loggers.getLogger(WatchTests.class); } - @Test - public void testParser_SelfGenerated() throws Exception { + public void testParserSelfGenerated() throws Exception { DateTime now = new DateTime(UTC); ClockMock clock = new ClockMock(); clock.setTime(now); @@ -223,8 +220,7 @@ public class WatchTests extends ESTestCase { assertThat(parsedWatch.actions(), equalTo(actions)); } - @Test - public void testParser_BadActions() throws Exception { + public void testParserBadActions() throws Exception { ClockMock clock = new ClockMock(); ScheduleRegistry scheduleRegistry = registry(randomSchedule()); TriggerEngine triggerEngine = new ParseOnlyScheduleTriggerEngine(Settings.EMPTY, scheduleRegistry, clock); @@ -254,8 +250,7 @@ public class WatchTests extends ESTestCase { } } - @Test - public void testParser_Defaults() throws Exception { + public void testParserDefaults() throws Exception { Schedule schedule = randomSchedule(); ScheduleRegistry scheduleRegistry = registry(schedule); TriggerEngine triggerEngine = new ParseOnlyScheduleTriggerEngine(Settings.EMPTY, scheduleRegistry, SystemClock.INSTANCE);